0

I am facing some issue while importing a class. The folder structure is as below:

python_space
  |_ __init__.py
  |_ ds_Tut
     |_ __init__.py
     |_ stacks
        |_ __init__.py
        |_ stacks.py  (contains class Stack)
     |_ trees
        |_ __init__.py
        |_ parseTree.py (wants to import Stack class from above)

Used the following code to import:

from stacks.stacks import Stack

Getting the following error:

"ImportError: No module named stacks.stacks"
Mazdak
  • 105,000
  • 18
  • 159
  • 188
Piklu Dey
  • 190
  • 1
  • 13
  • Where you used `from stacks.stacks import Stack`? – Mazdak Jul 05 '15 at 18:28
  • possible duplicate of [Python: Referencing another project](http://stackoverflow.com/questions/1476111/python-referencing-another-project) – Mazdak Jul 05 '15 at 18:33
  • possible duplicate of [Sibling package imports](http://stackoverflow.com/questions/6323860/sibling-package-imports) – talonmies Jul 05 '15 at 18:50

1 Answers1

0

stacks is inside the ds_Tut module. does this work?

from ds_Tut.stacks.stacks import Stack
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • ok, then what is the result of `import sys; print(sys.path)`? – hiro protagonist Jul 06 '15 at 17:19
  • the premise when creating packages is that the root directory of your package (`python_space`) is in your path. you should ensure that every executable adds this path in some way or other to the `PYTHONPATH`. – hiro protagonist Jul 06 '15 at 18:43
  • `['/home/piklu/python_space/ds_Tut/trees', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages']` This is the output of print(sys.path) – Piklu Dey Jul 07 '15 at 12:08
  • `/home/piklu/python_space/ds_Tut/trees` is the first entry: it should be `/home/piklu/python_space`. you need to set this either in python using `sys.path` or in the environment (your shell) in `PYTHONPATH`. – hiro protagonist Jul 07 '15 at 12:44
  • importing successfully now. Added: `import sys` `sys.path.insert(0, '/home/piklu/python_space')` inside parseTree.py – Piklu Dey Jul 07 '15 at 14:17
  • personally, inside a package i assume that the path is set correcly. i keep the executable scripts somewhere outside the package - they are responsible that the `PYTHONPATH` is set correctly. – hiro protagonist Jul 07 '15 at 14:38