New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
exec() issue when used inside function #80607
Comments
I've reported a stack overflow question and no reasonable explation was offered. Here is what I've discovered:
func() After This is the problem as long as the code is wrapped in function. If the same code is placed in the module body, works as expected. Is there any exaplanation for such behaviour, or is this a bug? |
Seems like I don't know how to write a code here. Works on 2.7, fails on everything above 3.x |
I test on 3.5 and 3.8 running not in an func and I don't have the problem: Python 3.8.0a2+ (heads/bpo-36287:ba8f342623, Mar 25 2019, 21:57:16)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'bar'
>>> b = 42
>>> c = a + ' = c'
>>> c
'bar = c'
>>> exec(c)
>>> 'bar' in locals()
True
>>> print(locals()['bar'])
bar = c
>>> print(bar)
bar = c
>>> print("'bar' OK:", bar)
'bar' OK: bar = c |
But I confirmed the behavior reported uhmm weird |
This is currently by design, which means 3.8 is likely the only viable place it can change. It's also not Windows specific so I removed that component (people may remove themselves from nosy). But +Nick, since I know he has some interest in making locals() behave more consistently. Currently it's basically a read-only proxy, as locals are optimized within functions which is why you can't see updates via the duct. |
This is not a bug; the behavior is covered in the docs. I am surprised that this works in 2.7, as it has the same warning as 3.7: |
Are there any workarounds - how can we use exec() and on-the-fly created variables? |
This is not a bug - to enable function level optimisations, the compiler must be able to see all local variable names at compile time. In Python 2.x the exec statement implementation included special code to allow even function local variables to be rebound, but that special-casing was removed as part of the Python 3 change to convert exec from a statement to a builtin function (as per https://www.python.org/dev/peps/pep-3100/#core-language ) This means that to use exec() and reliably see the changes it makes to a namespace, you have to supply a reliably read/write dictionary of your own. Object instance dictionaries work well for this purpose, as you can then access the results as attributes on the instance:
|
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: