In Python, how to import from the __init__.py in the same directory

后端 未结 2 441
庸人自扰
庸人自扰 2021-02-03 11:04

Suppose I have a module rules with the following structure:

rules
├── conditions.py
├── __init__.py

In the script conditions

2条回答
  •  走了就别回头了
    2021-02-03 11:30

    I see 'import from parent module' as an anti-pattern in Python. Imports should be the other way around. Importing from modules's __init__.py is especially problematic. As you noticed, importing module foo.bar from foo/bar.py involves importing foo/__init__.py first, and you may end up with a circular dependency. Adding a print("Importing", __name__) to your init files helps see the sequence and understand the problem.

    I'd suggest that you moved the code you want to import in conditions.py from __init__.py to a separate lower-level module, and just import some names from that module in __init__.py to expose it at higher level.

    Let's suppose that you had some class Bar in your __init__.py. I'd reorganize it the following way.

    __init__.py:

    from bar import Bar  # exposed at the higher level, as it used to be.
    

    bar.py:

    class Bar(object): ...
    

    conditions.py:

    from . import Bar  # Now it works.
    

    Ideally an __init__.py should contain nothing but imports from lower-level modules, or nothing at all.

提交回复
热议问题