How to fix “Attempted relative import in non-package” even with __init__.py

后端 未结 19 2618
予麋鹿
予麋鹿 2020-11-21 21:51

I\'m trying to follow PEP 328, with the following directory structure:

pkg/
  __init__.py
  components/
    core.py
    __init__.py
  tests/
    core_test.py         


        
19条回答
  •  星月不相逢
    2020-11-21 22:52

    As Paolo said, we have 2 invocation methods:

    1) python -m tests.core_test
    2) python tests/core_test.py
    

    One difference between them is sys.path[0] string. Since the interpret will search sys.path when doing import, we can do with tests/core_test.py:

    if __name__ == '__main__':
        import sys
        from pathlib import Path
        sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
        from components import core
        
    

    And more after this, we can run core_test.py with other methods:

    cd tests
    python core_test.py
    python -m core_test
    ...
    

    Note, py36 tested only.

提交回复
热议问题