Support relative imports in packages

Merged
R3
9d ago
+454-115

Part of #1275 (§2, "Packages and relative imports"); also needed for #1201 (Jinja2).

Relative imports (from . import x, from .mod import y, from .. import z, from .pkg.mod import w) now work in packages loaded from .py files.
Before this change every relative import raised ImportError: attempted relative import with no known parent package, which is the first thing blocking unittest and tomllib's internal modules.
Vendored stdlib packages (#1298) go through the same code and need no further change here.

Design

  • Parser: a relative import compiles to LoadModule with a name made only of dots (..), which loads the package. Each further component is a LoadSubmodule whose path keeps the dots (..pkg, ..pkg.mod).
    • No new opcode or operand.
    • No DUMP_VERSION bump: the parser used to reject these names, so no older dump can contain them.
  • VM: the dots are resolved when the import runs, against the frame's globals, the way CPython's _calc___package__ does:
    • It uses __package__.
    • Without __package__, it uses __name__, minus its last part unless __path__ is set.
    • It raises CPython's TypeError / KeyError for a non-string __package__ or __name__, or a missing __name__.
  • Loading: the package then loads the way import base would: built-in modules first, then cached and host modules. Submodules load by their full dotted name through the existing file-import code, so these behave as before:
    • from . import x falling back to the submodule x
    • circular imports and their "partially initialized module" message
    • "cannot import name" errors
  • Errors: they now happen when the statement runs, as in CPython, not when the code is compiled.
    • A relative import in a function that is never called no longer fails.
    • The main script, a top-level module, and the REPL still raise "attempted relative import with no known parent package".
    • Too many dots raise "attempted relative import beyond top-level package".
    • Errors name modules by their full name (No module named 'rel.nope'), never by the relative path.
    • The parse-time ParseError::Import is removed.

Tests

  • New import__relative.py (mount-fs), run on both Monty and CPython. It covers:
    • every import form above, in __init__ and in submodules, and inside a function that runs later
    • a circular import inside a package
    • going above the top-level package, and a top-level module with no package
    • missing modules and names, and a failing submodule
    • exec() with __package__ / __name__ / __path__ globals
    • a built-in module as the package (__package__ = 'os', 'os.path', 'sys'), including its "not a package" and "cannot import name" errors
    • a package whose import raised being imported again by a later relative import in one of its submodules
  • import__relative_error.py now also checks that the error is raised when the import runs, not when the file is compiled.
  • repl_rejected_snippet_locations drops its relative-import case, since that code is no longer rejected at compile time.
  • There is no test for vendored packages until #1298 lands and a package is vendored.

Documentation

  • limitations/language.md lists what still differs from CPython:
    • __spec__ is never read.
    • Falling back to __name__ gives no ImportWarning.
    • The main script and the REPL never have a package, even if they set __package__.
  • limitations/modules.md and docs/filesystem.md are updated to match.

Known gaps

  • A relative import whose package dropped out of the module cache (because its import raised) imports the package again only while the package's parent is still loaded. Otherwise it raises ModuleNotFoundError naming the package, where CPython would import the parent first, then the package. This is in limitations/language.md.

    Why: one LoadModule / LoadSubmodule instruction performs one import step: it returns a cached module, asks the host, or runs one module body. Any step can pause for the host or push a module-body frame, and the instruction ends when that one module is pushed. import a.b.c gets one instruction per level from the compiler, but a relative import's depth depends on __package__ at runtime, so the compiler can't emit the chain.

    Fixing it would mean re-running the instruction after each level, with the intermediate module thrown away. That touches the three ways an import can finish (host value, host file, vendored module), the frame return path and SerializedFrame. Roughly 100–150 lines for a case that only follows an already-failed import, or exec() with a hand-written __package__. importlib.import_module / __import__ will need the same chained imports, so it's better built once, then.

    After a failed import, CPython usually re-runs the failing __init__ and raises its error again, so only the error differs. With exec() and a __package__ naming a package nobody imported, CPython can succeed where Monty raises.