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}
You can get the cell contents by checking out
f.func_closure
(works in Python 2.7.5):Python 3.3 has an
inspect.getclosurevars
function:I'm not yet sure if you can get the closed-over variable names pre-Python 3.3.
Python 3 Update - Feb 2019
Purposely, writing this out long-hand:
What I am less clear on, and this applies to the answer marked correct above also, is whether the ordering between the tuple of (non-local closure) variable names (
__code__.co_freevars
) and the ordering of the variable values (f2.__closure__
) are guaranteed to match (which thezip
operation depends upon). In the simple example used to ask the question, we are only dealing with a single variablex
so the above would suffice for that specific case.Be good if anyone can confirm the general case rather than just assume it to be so?
You don't have to use the
inspect
module here.works in Python 2.7