Re: How to get the closure environment in Python?

2016-04-28 Thread Rob Gaddi
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.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to get the closure environment in Python?

2016-04-28 Thread Steven D'Aprano
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

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to get the closure environment in Python?

2016-04-28 Thread Yuan Cao
On Thu, Apr 28, 2016 at 12:23 PM, 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
> --
> 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