How to get the closure environment in Python?
Steven D'Aprano
steve at pearwood.info
Thu Apr 28 12:46:31 EDT 2016
On Fri, 29 Apr 2016 02:23 am, Jin Li wrote:
> I want to get the closure environment in Python. As in the following
> example:
>
> def func1():
> x = 10
> def func2():
> return 0
> return func2
>
> f=func1()
> print f()
>
>
> How could I get the variable `x` in the environment of `func2()`? i.e.
> `f()`.
In this case, you can't, because f is not a closure. The inner function has
to actually use a variable from the enclosing scope to be a closure -- it's
just a regular function that simply returns 0. The enclosing x does
nothing.
You can see this by inspecting f.__closure__, which is None.
If we use a better example:
def outer():
x = 10
def inner():
return x + 1
return inner
f = outer()
then you can inspect
f.__closure__[0].cell_contents
which will return 10 (the value of x).
--
Steven
More information about the Python-list
mailing list