Skip to content

global declaration in except has incorrect prior use #111123

Closed
@15r10nk

Description

@15r10nk

Bug report

Bug description:

I think the global a has 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.

a=5

def f():
    try:
        pass
    except:
        global a
    else:
        print(a)

output (Python 3.12.0):

  File "/home/frank/projects/pysource-playground/pysource-codegen/bug.py", line 8
    global a
    ^^^^^^^^
SyntaxError: name 'a' is used prior to global declaration

the following code has no syntax error:

a=5

def f():
    try:
        pass
    except:
        global a
    print(a)

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions