Skip to content

Imports in a finally or else clause are lazy under __lazy_modules__ #162573

Backlog

Description

@Robertboy18

Bug report

Bug description:

The docs say "Imports inside functions, class bodies, or try/except/finally blocks are always eager, regardless of __lazy_modules__" (Compatibility via __lazy_modules__), and lazy import in a finally or else clause is a SyntaxError ("lazy import not allowed inside try/except blocks"). Imports in the try and except bodies are eager, but one in the finally clause, on the normal path, or in the else clause of a try without finally is lazy:

__lazy_modules__ = ["ast", "json"]
try:
    pass
except ImportError:
    pass
else:
    import ast
try:
    raise KeyError
except KeyError:
    pass
finally:
    import json
print(type(globals()["ast"]).__name__, type(globals()["json"]).__name__)
lazy_import lazy_import

I expected module module. The normal-path copy of the finally body (codegen_try_finally in Python/codegen.c) and the else body are compiled outside the fblocks that _PyCompile_InExceptionHandler checks. 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
    interpreter-core
    type-bug
    on Nov 24, 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-lazy-importstype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions