Search code examples
pythonpython-importrelative-path

How to do relative imports in Python with this structure?


Imagine I have this structure :

dir/
   __init__.py
   dir1/
       __init__.py
       x.py
   dir2/
       __init__.py
       y.py

Now I want to import x.py to y.py .
I try this from ..dir1.x import * in y.py from PEP 328 but I get this error Attempted relative import in non-package .
I search for hours but I can not find any answer to this problem .
There are a lot of similar problems like mine but none of them help me like this
Please help .
Thanks a lot .


Solution

  • in y.py, add this piece of import code

    import sys
    sys.path.insert(0, '..')
    

    then do

    from dir1.x import *