2

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 .

Machavity
  • 30,841
  • 27
  • 92
  • 100
user31587
  • 145
  • 1
  • 9
  • In the surface this looks like an exact duplicate of the other question you linked to; you should probably explain why that solution didn't work for you here. – Michael Edenfield Jan 18 '13 at 20:50
  • you are right but if i know what the problem is i don't ask it again . i asks this question again to find the problem . – user31587 Jan 18 '13 at 21:05

2 Answers2

0

Relative imports won't work when files are invocated directly:

python y.py

since they have __name__ == '__main__' instead of their full package name.

For the relative import to work you must use y as a package:

python -m dir.dir2.y
Yuval Adam
  • 161,610
  • 92
  • 305
  • 395
  • thanks a lot . but i am new to python . how i could run the last command ? i use windows . – user31587 Jan 18 '13 at 20:38
  • i use this in cmd in the python folder : python -m c:\Users\my_user_name\Desktop\dir\dir2\y but i get this error : no module named c:\Users\my_user_name\Desktop\dir\dir2\y – user31587 Jan 18 '13 at 20:55
0

in y.py, add this piece of import code

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

then do

from dir1.x import *
nye17
  • 12,857
  • 11
  • 58
  • 68
  • thanks a lot but what was the first import do ? i think it is work but it isn't clean way to do this . – user31587 Jan 19 '13 at 05:11
  • @XLichking first import to make sure the parent directory is under the search path of your python, so that it could recognize dir1 as a valid module to import. It doesn't look clean simply because what you asked for is not a natural thing to do in python in the first place. – nye17 Jan 19 '13 at 05:40
  • thanks a lot but how i could change my structure to be normal ? – user31587 Jan 19 '13 at 06:00
  • @XLichking you could either reorganize your modules so that submodules don't depend on each other, or you could try to do everything in the root directory, e.g., writing a `main.py` file under `dir` to import `dir1` and `dir2` and doing things there. – nye17 Jan 19 '13 at 06:30