Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

python - ValueError: Attempted relative import in non-package not for tests package

I know this has been asked many times but somehow I am not able to get over this error. Here is my directory structure-

project/
  pkg/
  __init__.py
  subpackage1/
        script1.py
        __init__.py
  subpackage2/
        script2.py
       __init__.py

script2.py has:

class myclass:
    def myfunction:

script1.py has

 from ..subpackage2 import script2   

I also tried

from ..subpackage2 import myclass

And this gives me : ValueError: Attempted relative import in non-package

Any help would be really appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This answer explains what's going on: https://stackoverflow.com/a/73149/769971

You're probably running script1.py from inside the subpackage1/ directory. Change your import to be from subpackage2 import script2, back up to the pkg/ directory, then run python -m subpackage1.script1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...