Relative import problems in Python 3

后端 未结 7 983
庸人自扰
庸人自扰 2021-02-13 21:01

Python imports drive me crazy (my experience with python imports sometime doesn\'t correspond at all to idiom \'Explicit is better than implicit\' :( ):

[app]
           


        
7条回答
  •  误落风尘
    2021-02-13 21:45

    Your update emulates what the absolute import does: import package1.module1 if you do it while module1 being imported. If you'd like to use a dynamic parent package name then to import module1 in the module2.py:

    import importlib
    module1 = importlib.import_module('.module1', __package__)
    

    I need circular imports. A function in module1 asserts that one of its parameter is instance of a class defined in module2 and viceversa.

    You could move one the classes to a separate module to resolve the circular dependency or make the import at a function level if you don't want to use absolute imports.

    .
    ├── start.py
    #       from package1 import module1
    └── package1
        ├── __init__.py
    #           print("Init package1")
    #           from . import module1, module2
        ├── c1.py
    #           print("Init package1.c1")
    #           class C1:
    #               pass
        ├── module1.py
    #           print("Init package1.module1")
    #           from .c1 import C1
    #           from .module2 import C2
        └── module2.py
    #           print("Init package1.module2")
    #           from .c1 import C1
    #           class C2:
    #               pass
    #           def f():
    #               from .module1 import C1
    

    Output

    Init package1
    Init package1.module1
    Init package1.c1
    Init package1.module2
    

    Another option that might be simpler than refactoring out c1.py is to merge module{1,2}.py into a single common.py. module{1,2}.py make the imports from common in this case.

提交回复
热议问题