Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #105475 > unrolled thread
| Started by | Steven D'Aprano <steve@pearwood.info> |
|---|---|
| First post | 2016-03-22 23:57 +1100 |
| Last post | 2016-03-23 00:31 +1100 |
| Articles | 2 — 2 participants |
Back to article view | Back to comp.lang.python
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
| From | Steven D'Aprano <steve@pearwood.info> |
|---|---|
| Date | 2016-03-22 23:57 +1100 |
| Subject | exec inside functions in Python 3 |
| Message-ID | <56f14156$0$1619$c3e8da3$5496439d@news.astraweb.com> |
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?
--
Steven
[toc] | [next] | [standalone]
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2016-03-23 00:31 +1100 |
| Message-ID | <mailman.12.1458653508.2244.python-list@python.org> |
| In reply to | #105475 |
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
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web