beyond top level package error in relative import

后端 未结 13 2520
醉梦人生
醉梦人生 2020-11-22 12:50

It seems there are already quite some questions here about relative import in python 3, but after going through many of them I still didn\'t find the answer for my issue. s

13条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 13:15

    In my humble opinion, I understand this question in this way:

    [CASE 1] When you start an absolute-import like

    python -m test_A.test
    

    or

    import test_A.test
    

    or

    from test_A import test
    

    you're actually setting the import-anchor to be test_A, in other word, top-level package is test_A . So, when we have test.py do from ..A import xxx, you are escaping from the anchor, and Python does not allow this.

    [CASE 2] When you do

    python -m package.test_A.test
    

    or

    from package.test_A import test
    

    your anchor becomes package, so package/test_A/test.py doing from ..A import xxx does not escape the anchor(still inside package folder), and Python happily accepts this.

    In short:

    • Absolute-import changes current anchor (=redefines what is the top-level package);
    • Relative-import does not change the anchor but confines to it.

    Furthermore, we can use full-qualified module name(FQMN) to inspect this problem.

    Check FQMN in each case:

    • [CASE2] test.__name__ = package.test_A.test
    • [CASE1] test.__name__ = test_A.test

    So, for CASE2, an from .. import xxx will result in a new module with FQMN=package.xxx, which is acceptable.

    While for CASE1, the .. from within from .. import xxx will jump out of the starting node(anchor) of test_A, and this is NOT allowed by Python.

提交回复
热议问题