[Python-Dev] About closures creates in exec

2015-08-12 Thread Andrea Griffini
Is it intended that closures created in exec statement/function cannot see
locals if the exec was provided a locals dictionary?

This code gives an error (foo is not found during lambda execution):

exec(def foo(x): return x\n\n(lambda x:foo(x))(0), globals(), {})

while executes normally with

exec(def foo(x): return x\n\n(lambda x:foo(x))(0))

Is this the expected behavior? If so where is it documented?

Andrea
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] About closures creates in exec

2015-08-12 Thread R. David Murray
On Wed, 12 Aug 2015 21:05:50 +0200, Andrea Griffini agr...@tin.it wrote:
 Is it intended that closures created in exec statement/function cannot see
 locals if the exec was provided a locals dictionary?
 
 This code gives an error (foo is not found during lambda execution):
 
 exec(def foo(x): return x\n\n(lambda x:foo(x))(0), globals(), {})
 
 while executes normally with
 
 exec(def foo(x): return x\n\n(lambda x:foo(x))(0))
 
 Is this the expected behavior? If so where is it documented?

Yes.  In the 'exec' docs, indirectly.  They say:

Remember that at module level, globals and locals are the same
dictionary. If exec gets two separate objects as globals and locals, the
code will be executed as if it were embedded in a class definition.

Try the above in a class def and you'll see you get the same behavior.

See also issue 24800.  I'm wondering if the exec docs need to talk about
this a little bit more, or maybe we need a faq entry and a link to it?

--David
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com