1

I am unable to get the following things to work simultaneously in Python2.7:

  • import submodules from a local package

  • import submodules from the package when it is on the PYTHONPATH

I have set up the sample directory structure as in the python docs for packages

 cd tmp
 mkdir sound
 mkdir sound/formats
 mkdir sound/effects
 mkdir sound/filters
 cd sound
 touch __init__.py
 cp !$ formats/
 cp __init__.py formats/
 cp __init__.py effects/
 cp __init__.py filters/
 echo "def echofilter(): return(1) " > effects/echo.py
 cd ../..

So, I end up with:

$ ls tmp/sound
effects/  filters/  formats/  __init__.py

If I make the package local, as it would be if it were acting as a git submodule, for instance, ie by cd tmp, the following is successful:

$ python
Python 2.7.10 (default, Oct 14 2015, 16:09:02) 
[GCC 5.2.1 20151010] on linux2
>>> from sound.effects import echo
>>> 

Yet if I am located somewhere else (cd ..), and I put the package on my PYTHONPATH, I cannot import as in the docs:

[~/tmp]$ cd ..
[~]$ python
Python 2.7.10 (default, Oct 14 2015, 16:09:02) 
[GCC 5.2.1 20151010] on linux2
>>> import sys
>>> sys.path.append('/home/meuser/tmp/sound')
>>> from sound.effects import echo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named sound.effects
>>> sys.path.append('/home/meuser/tmp/sound/effects')
>>> from sound.effects import echo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named sound.effects

So how am I supposed to arrange things?

2
  • So let me get this straight: you want to be able to import this package you've made from anywhere on the machine? Commented Mar 4, 2016 at 16:35
  • Yes. I have certain packages that I maintain and use for lots of projects. I put their location in my PYTHONPATH (isn't that what it's for?), set in my bash configuration. In fact, that's how I've done it for many years, but I never used dots to specify submodules (sound.effects). Instead, I just had a bunch of files (modules) at the same level under sound/ , from which I would import explicitly. Commented Mar 4, 2016 at 18:51

1 Answer 1

1

Ah! If it's a package, I need the folder containing the package (ie ~/tmp/) in my path, not the folder of the package itself (~/tmp/sound). Thus, the following works:

>>> import sys
>>> sys.path.append('/home/meuser/tmp/')
>>> from sound.effects import echo

Now I believe this solves all my recent conundrums..

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.