The file structure is as follows
python_directory/__init__.pyapp __init__.py sub1 __init__.py mod1.py sub2 __init__.py mod2.py
In addition to mod1.py, the contents of other files are empty.
mod1.py
print('__name__: {}'.format(__name__))print('__package__: {}'.format(__package__))fromimport mod2print('Import Successfully!')
If __package__ not NULL, the relative reference is based __package__ instead of __name__ [2].
Relative Import in Non-package
If a module is executed directly, then it __name__ is __main__ . Python will consider this module to be the topmost module, regardless of the actual location of the module in the file system [1].
pwd/path_to/python_directorypython__name__: __main____package__: NoneTraceback (most recent call last): File"app/sub1/mod1.py"<module> from ..sub2 import mod2ValueError: Attempted relative import in non-package
一个最顶层的模块--I understand that for Python to copy this module into a separate directory and then execute it, because there's only one module in that directory,
So it's not a package.
Beyond Top Level Package
$pwd/path_to/python_directory/app$python-M SUB1.MOD1__name__: __main____package__: Sub1Traceback(most recent): File "/usr/local/cellar/python/2.7.13/frameworks/python.framework/versions/2.7/lib/python2.7/runpy.py", line 174, in _run_module_as_main"__main__",fname, loader, Pkg_name)File "/usr/local/cellar/python/2.7.13/frameworks/python.framework/versions/2.7/lib/python2.7/runpy.py", line at _run_codeexecCode in Run_globalsFile "/path_to/python_directory/app/sub1/mod1.py", line 4, in<Module> from.. SUB2 Import Mod2ValueError: Attempted relative import beyond TopLevel package
Because -m sub1.mod1 Python treats the top layer of the package as if it is, above the current topmost level, it sub1 ..sub2 is an app/ sub1 error.
└── app ├── __init__.py ├── sub1 │?? ├── __init__.py │?? └── mod1.py └── sub2
The correct invocation
pwd/path_to/python_directorypython -m app.sub1.mod1__name__: __main____package__: app.sub1Import Successfully!
This is the ..sub2 equivalent app.sub2 .
Reference
- PEP 328--Imports:multi-line and Absolute/relative
- PEP 366--Main module Explicit relative imports
Python Module Relative Reference