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
global declaration in except has incorrect prior use #111123
Comments
|
I feel like this issue might be interesting to @iritkatriel and @pablogsal. |
|
I think this is because |
|
The converse of this bug is that this code currently works (and prints 1): a = 0
def f():
try:
1 / 0
except:
a = 1
else:
global a
f()
print(a)With Irit's fix, this would instead be a SyntaxError. I don't know if any code in existence would rely on this weird behavior, but we should probably fix this only on main (not the bugfix branches) and call out the change in behavior in What's New. |
|
I agree @JelleZijlstra I think I understood how the logic behind a=0
def f(cnd,value):
if cnd:
global a
a=value
f(True,1)
print(a)
f(False,2)
print(a)output (Python 3.12.0): 1
2global is not affected by the actual order of execution. It is more "the line" in which it was declared. The syntax error for prior use exists mainly to safe the user from thinking that he could put the global behind the use of some variable and to expect a different behavior. A @iritkatriel I saw your fix and I think |
Right, thanks. |
Bug report
Bug description:
I think the
global ahas no prior use in this code (and pyright tells me the same). But I don't understand why cpython thinks it has a prior use.output (Python 3.12.0):
the following code has no syntax error:
I can also reproduce this issue in 3.7.
I also don't know what the exact semantic of global/nonlocal inside statements like if/while/try/... is. I would like to know more about it because I'm currently writing pysource-codegen where I generate such cases.
CPython versions tested on:
3.12
Operating systems tested on:
Linux
Linked PRs
The text was updated successfully, but these errors were encountered: