Skip to content

Global and nonlocal exception aliases are removed from scope #127771

@noahbkim

Description

@noahbkim

Bug report

Bug description:

When you alias an exception caught in except to a global or nonlocal name, that name will be removed from its original scope. For global:

error = None

def f():
    global error
    try:
        raise ValueError()
    except ValueError as error:
        pass

# Output
error before: None
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    print(f"error after: {error}")
                          ^^^^^
NameError: name 'error' is not defined. Did you mean: 'OSError'?

For nonlocal:

def g():
    error = None

    def f():
        nonlocal error
        try:
            raise ValueError()
        except ValueError as error:
            pass

    print(f"error before: {error}")
    f()
    print(f"error after: {error}")

g()

# Output
error before: None
Traceback (most recent call last):
  File "test.py", line 16, in <module>
    g()
  File "test.py", line 13, in g
    print(f"error after: {error}")
                          ^^^^^
UnboundLocalError: cannot access local variable 'error' where it is not associated with a value

This is a bit counterintuitive. Is it intended behavior for any reason?

CPython versions tested on:

3.12

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    pendingThe issue will be closed if no feedback is providedtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions