If I have:
def f(x):
def g(y):
return x + y
return g
f2 = f(2)
Is there a way to find the x
binding that f2
will use? I looked at inspect
but could not tell if some of the frame
stuff would apply. In other words, could I define a closed_vars()
below:
def closed_vars(anF):
... return ...
assert closedVars(f2) == {'x': 2}
A closure is a function object that remembers values in enclosing scopes even if they are not present in memory. The __closure__ attribute of a closure function returns a tuple of cell objects. This cell object also has an attribute called cell_contents, which returns returns the contents of the cell.
Python Decorators make an extensive use of closures as well. On a concluding note, it is good to point out that the values that get enclosed in the closure function can be found out. All function objects have a __closure__ attribute that returns a tuple of cell objects if it is a closure function.
inspect. stack() returns a list with frame records. In function whoami() : inspect. stack()[1] is the frame record of the function that calls whoami , like foo() and bar() . The fourth element of the frame record ( inspect.
You don't have to use the inspect
module here.
>>> dict(zip(f2.func_code.co_freevars, (c.cell_contents for c in f2.func_closure)))
{'x': 2}
works in Python 2.7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With