What is a Python Closure?
a) A function object that remembers values from its enclosing lexical scope even when the program flow is no longer in that scope
b) A function that is returned by another function
c) A way to define a function without a name
d) A method for encapsulating data in classes
Answer:
a) A function object that remembers values from its enclosing lexical scope even when the program flow is no longer in that scope
Explanation:
A Python closure is a function object that captures and remembers the values from its enclosing lexical scope even when the function is called outside that scope. Closures are useful for maintaining state across multiple calls to a function without using global variables.
def outer_function(msg):
def inner_function():
print(msg)
return inner_function
my_func = outer_function("Hello, World!")
my_func() # Output: Hello, World!
In this example, inner_function()
is a closure that captures the value of msg
from outer_function()
. When my_func()
is called, it prints the message stored in the closure.
Closures are often used in functional programming paradigms, allowing for the creation of functions with customized behavior or state that persists across invocations.