exec inside functions in Python 3

Chris Angelico rosuav at gmail.com
Tue Mar 22 09:31:45 EDT 2016


On Tue, Mar 22, 2016 at 11:57 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> Anyone have any idea what is going on here?
>
>
> def test():
>     spam = 1
>     exec("spam = 2; print('inside exec: %d' % spam)")
>     print('outside exec: %d' % spam)
>
>
> In Python 2.7:
>
> py> test()
> inside exec: 2
> outside exec: 2
>
>
>
> In Python 3.4:
>
> outside exec: 1
> py> test()
> inside exec: 2
> outside exec: 1
>
>
>
> What happened to spam?

In Python 2, exec is magical. In Python 3, it's a function like any
other, so it doesn't have access to local variables; what it gets is
locals(), which is a one-way representation of current locals -
changes don't propagate back.

It'd maybe be nice to be able to tell Python to compile a function
with a "real locals dictionary", which would then be mutated by
locals() changes (as locals() would simply return it as-is). That'd
fix this "problem", if problem it indeed is.

ChrisA



More information about the Python-list mailing list