Python3模块布局与导入规则的定义出处及版本适配方案咨询
What Changed in Python's Import Mechanism?
The root issue here is Python 3's elimination of implicit relative imports, a change formalized in PEP 328.
In Python 2, when you wrote import _mymodule inside mymodule/__init__.py, Python would first check the current package directory (the mymodule folder) for the shared object file. This was an implicit relative import—Python assumed you meant the module in the same package without requiring explicit syntax.
Python 3 replaced this behavior with absolute imports as the default. Now, import _mymodule in __init__.py tells Python to look for a top-level _mymodule module in directories listed in PYTHONPATH, not the current package. That’s why you had to add the mymodule subdirectory to PYTHONPATH—to trick Python into treating _mymodule as a standalone top-level module.
Correct Handling for mymodule
You have two clean, Python 3-compliant solutions that don’t require modifying PYTHONPATH:
Explicit Relative Import
Use a dot to explicitly reference the current package inmymodule/__init__.py:from . import _mymodule # To import all symbols directly into the package namespace: from ._mymodule import *The dot signals to Python that you want the module inside the same
mymodulepackage.Absolute Import Using the Package Name
Follow thetyped_astpattern, using the full package path to reference the submodule:from mymodule import _mymodule # Or: from mymodule._mymodule import *Since
mymoduleis recognized as a package (thanks to__init__.py), Python resolves_mymoduleas a submodule ofmymodulewithout needing extraPYTHONPATHconfiguration.
Where Are These Rules Defined?
- PEP 328 – Imports: Multi-Line and Absolute/Relative: This PEP outlines the shift to absolute imports as the default in Python 3, and introduces explicit relative imports (using dots) for intra-package references.
- Python Official Documentation: The Intra-Package Imports section of the import system docs explains how to reference submodules within a package using both absolute and explicit relative syntax.
内容的提问来源于stack exchange,提问作者dvhart

