Skip to content

An import of a name before its global or nonlocal declaration is not a SyntaxError #162598

Backlog

Description

@Robertboy18

Bug report

Bug description:

The Reference says "A SyntaxError is raised if a variable is used or assigned to prior to its global declaration in the scope" (global), the same for nonlocal, and an import binds names "just as an assignment statement would (including global and nonlocal semantics)". An assignment before global x is rejected, an import is not:

>>> def f():
...     x = 1
...     global x
...     
  File "<python-input-1>", line 3
    global x
    ^^^^^^^^
SyntaxError: name 'x' is assigned to before global declaration

>>> def f():
...     import x
...     global x
... 
>>> 

>>> def f():
...     from os import x
...     global x
>>>

CPython 3.15.2 and main (639c34b):

The import then binds the global, and the same happens before nonlocal x and at module level. The check for Global_kind and Nonlocal_kind in symtable_visit_stmt (Python/symtable.c) tests DEF_PARAM | DEF_LOCAL | USE | DEF_ANNOT but not DEF_IMPORT. I found it while writing a Lean spec of Python.

CPython versions tested on:

3.15, CPython main branch

Operating systems tested on:

Linux

Activity

  1. added
    AI-needs-explanation
    on Nov 25, 2026
  2. bedevere-app commented on Nov 25, 2026

    @bedevere-app

    Thank you for taking the time to open this issue. Python is a community-driven project, and we want it to be a welcoming place to learn and collaborate.

    This issue appears to have been written with AI assistance. Please explain your issue in your own words and describe how you checked the information you provided. This helps us understand your issue and leaves more time to address other issues.

    Please read our guidelines for using AI tools.

  3. picnixz commented on Nov 25, 2026

    @picnixz
    Member

    @Robertboy18 Your reproducers are very hard to read. PLease don't use a loop with compile/exec and newlines it's impossible to reproduce easily on our side and investigate.

  4. added
    type-bug
    interpreter-core
    and removed
    AI-needs-explanation
    on Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-coretopic-parsertype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions