17

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.

codec
  • 7,978
  • 26
  • 71
  • 127
  • Possible duplicate of [How to do relative imports in Python?](http://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python) – ganchito55 May 12 '16 at 21:46

1 Answers1

21

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.

Community
  • 1
  • 1
wholevinski
  • 3,658
  • 17
  • 23
  • 3
    this works for me. I think my error was trying to run python script with `python ./subpackage1/script1.py` instead of `python -m subpackage1.script1`, it is totally wrong!!! – penny chan Jul 17 '17 at 08:56