prj
-pkg_1
--file1.py
-pkg_2
--file2.py
在file2.py
内,我们有类似的内容:
# Ye be in dis 'ere file which be name-ed `file2.py`
if __name__ == '__main__':
## MAGICAL IMPORT STATEMENT HERE ###
# import Klass from pkg_1/file1.py
# definitely do not write `from . [blah, blah, blah]`
# NO DOTS ALLOWED AFTER `from` inside main script!
else: # We not be da main script
from ..pkg_1.file1 import Klass
# go to parent directory of current file
# (parent dir of `file2.py` is `pkg2`)
# go to parent_directory_of(`pkg2`) == `proj`
# look for `pkg_1` under `proj`
# look for `file1` under `pkg_1`
# look for `Klass` inside `file1`
我们可以将MAGICAL IMPORT STATEMENT
替换为什么?如果我们将file2.py
作为主脚本运行,我们就不会"ValueError: attempted relative import beyond top-level package"