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

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

    Issue is with your testing method,

    you tried python core_test.py

    then you will get this error ValueError: Attempted relative import in non-package

    Reason: you are testing your packaging from non-package source.

    so test your module from package source.

    if this is your project structure,

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

    cd pkg

    python -m tests.core_test # dont use .py
    

    or from outside pkg/

    python -m pkg.tests.core_test
    

    single . if you want to import from folder in same directory . for each step back add one more.

    hi/
      hello.py
    how.py
    

    in how.py

    from .hi import hello
    

    incase if you want to import how from hello.py

    from .. import how
    

提交回复
热议问题