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

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

    If someone is looking for a workaround, I stumbled upon one. Here's a bit of context. I wanted to test out one of the methods I've in a file. When I run it from within

    if __name__ == "__main__":
    

    it always complained of the relative imports. I tried to apply the above solutions, but failed to work, since there were many nested files, each with multiple imports.

    Here's what I did. I just created a launcher, an external program that would import necessary methods and call them. Though, not a great solution, it works.

提交回复
热议问题