You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3模块布局与导入规则的定义出处及版本适配方案咨询

Python 2 vs 3 Import Mechanism Differences & Module Best Practices

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:

  1. Explicit Relative Import
    Use a dot to explicitly reference the current package in mymodule/__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 mymodule package.

  2. Absolute Import Using the Package Name
    Follow the typed_ast pattern, using the full package path to reference the submodule:

    from mymodule import _mymodule
    # Or:
    from mymodule._mymodule import *
    

    Since mymodule is recognized as a package (thanks to __init__.py), Python resolves _mymodule as a submodule of mymodule without needing extra PYTHONPATH configuration.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:20:10