Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #105483
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: exec inside functions in Python 3 |
| Date | 2016-03-23 00:31 +1100 |
| Message-ID | <mailman.12.1458653508.2244.python-list@python.org> (permalink) |
| References | <56f14156$0$1619$c3e8da3$5496439d@news.astraweb.com> |
On Tue, Mar 22, 2016 at 11:57 PM, Steven D'Aprano <steve@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
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
exec inside functions in Python 3 Steven D'Aprano <steve@pearwood.info> - 2016-03-22 23:57 +1100 Re: exec inside functions in Python 3 Chris Angelico <rosuav@gmail.com> - 2016-03-23 00:31 +1100
csiph-web