Support relative imports in packages
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
LoadModulewith a name made only of dots (..), which loads the package. Each further component is aLoadSubmodulewhose path keeps the dots (..pkg,..pkg.mod).- No new opcode or operand.
- No
DUMP_VERSIONbump: 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/KeyErrorfor a non-string__package__or__name__, or a missing__name__.
- It uses
- Loading: the package then loads the way
import basewould: 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 xfalling back to the submodulex- 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::Importis 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
- every import form above, in
import__relative_error.pynow also checks that the error is raised when the import runs, not when the file is compiled.repl_rejected_snippet_locationsdrops 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.mdlists what still differs from CPython:__spec__is never read.- Falling back to
__name__gives noImportWarning. - The main script and the REPL never have a package, even if they set
__package__.
limitations/modules.mdanddocs/filesystem.mdare 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
ModuleNotFoundErrornaming the package, where CPython would import the parent first, then the package. This is inlimitations/language.md.Why: one
LoadModule/LoadSubmoduleinstruction 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.cgets 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, orexec()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. Withexec()and a__package__naming a package nobody imported, CPython can succeed where Monty raises.