how to add a package to sys path for testing

Try adding an empty __init__.py to tests/: touch tests/__init__.py should do it.


Question: How can I add my sample package to the sys path correctly?

You're doing it the right way, but you missed declaring your folder to be a package. Try solution of Christian, it should work.

Your path is stored in sys.path. By doing this:

sys.path.insert(0, os.path.abspath('..'))

You're telling your python to add upper folder (of current file) into your path. As sys.path is a list, you can using other methods of list like insert, append...

In your case, you're inserting your upper dir at top of the path list.

See:

In [1]: import sys

In [2]: sys.path
Out[2]: 
['',
 '/usr/local/bin',
 '/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',
 '/usr/local/lib/python3.4/dist-packages/IPython/extensions',
 '/home/cuong/.ipython']

In [3]: sys.path.insert(0, '/tmp/foo')

In [4]: sys.path
Out[4]: 
['/tmp/foo', **<-- on top**
 '',
 '/usr/local/bin',
 '/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',
 '/usr/local/lib/python3.4/dist-packages/IPython/extensions',
 '/home/cuong/.ipython']

So, from here, when you have

import sample

your python will try to look in path to see if there is any sample package.

Unfortunately, it can't find sample as you didn't make it as a package because your forgot __init__.py in sample folder.

Hope my explanation would help you to understand and you can handle other situations different to this.

Tags:

Python