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
  2. vyankateshk97 commented on Nov 25, 2026

    @vyankateshk97

    Hi @Robertboy18,

    I would like to work on this #162573 issue. I plan to reproduce the behavior on the CPython Fork branch, investigate the compiler handling of imports in else and finally clauses, and implement a fix with regression tests. Please let me know if anyone is already working on this.
    Thank you!

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