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

后端 未结 19 2572
予麋鹿
予麋鹿 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:31

    This approach worked for me and is less cluttered than some solutions:

    try:
      from ..components.core import GameLoopEvents
    except ValueError:
      from components.core import GameLoopEvents
    

    The parent directory is in my PYTHONPATH, and there are __init__.py files in the parent directory and this directory.

    The above always worked in python 2, but python 3 sometimes hit an ImportError or ModuleNotFoundError (the latter is new in python 3.6 and a subclass of ImportError), so the following tweak works for me in both python 2 and 3:

    try:
      from ..components.core import GameLoopEvents
    except ( ValueError, ImportError):
      from components.core import GameLoopEvents
    

提交回复
热议问题