How do closures and late binding work in Python?

Closures and late binding in Python refer to the concept of nested functions and how they capture the state of their enclosing scope. A closure occurs when a nested function remembers its enclosing scope, allowing it to access variables from that scope even after the outer function has finished executing. Late binding refers to the way in which the values of variables are looked up when the nested function is called, which may differ from their values at the time the closure was created.

Example of Closure and Late Binding

def outer_function(x): def inner_function(y): return x + y return inner_function # Create a closure closure = outer_function(10) # Late binding: x will be evaluated when inner_function is called. print(closure(5)) # Output: 15 print(closure(20)) # Output: 30

closures late binding Python nested functions scope programming