On Thu, Apr 28, 2016 at 12:23 PM, Jin Li <lijin....@gmail.com> 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 > -- > https://mail.python.org/mailman/listinfo/python-list Hello, You can sort of look into the underlying code by using __code__, and it's associated methods. I was able to get the variable names with: print(funct1.__code__.co_varnames). I was sort of able to get to the value 10 with: print(func1.__code__.co_consts). This way seems pretty messy. Other people probably have more elegant ways of doing this. I hope this helps. Best Regards, Yuan -- https://mail.python.org/mailman/listinfo/python-list