[Python-Dev] About closures creates in exec

R. David Murray rdmurray at bitdance.com
Wed Aug 12 21:48:25 CEST 2015


On Wed, 12 Aug 2015 21:05:50 +0200, Andrea Griffini <agriff at 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


More information about the Python-Dev mailing list