How to get the closure environment in Python?

Rob Gaddi rgaddi at highlandtechnology.invalid
Thu Apr 28 12:42:02 EDT 2016


Jin Li wrote:

> Hi all,
>
> 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()`.
>
> Best regards,
> Jin

By using class instances instead of closures.

class Foo:
  def __init__(self, x):
    self.x == x

  def __call__(self):
    return 0

def func1():
  return Foo(10)

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.



More information about the Python-list mailing list