0
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"

4

0 回答 0