Chapter 4: Python modules

Searching for modules

face Josiah Wang

We have so far assumed that your modules are placed in the same directory as your script.

What if your module is located somewhere else? Perhaps it’s a library that you have written separately for another project?

Where does Python search for my modules?

When we say import libmonster, Python will first search the current directory for this module.

If it is not found, then Python will search sys.path (which is a list) that stores all the directories it should search when it attempts to import a module.

>>> import sys
>>> print(sys.path)
['', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/user/.local/lib/python3.8/site-packages', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages']

Check out your sys.path now! You will probably see some directories pointing to your Python installation folder - that is how Python searches for modules like random and os in the standard library.

If my_module is somewhere else, then you will have to add this location to sys.path before you import the module. Since sys.path is a list, use the append() method.

>>> import sys
>>> sys.path.append("wherever/you/have/put/your/module/")
>>> import libmonster

Python should then be able to find your module where you specified it.

If you are on Linux/UNIX/macOS, you can also append the path to the PYTHONPATH environment variable. If you check sys.path after this, you should find the path you defined in sys.path.

user@MACHINE:~$ export PYTHONPATH=${PYTHONPATH}:path/to/mylib

Try it yourself!

Now, just do a quick exercise. Move libmonster.py into a subfolder, say to mylib/libmonster.py. Then try running python3 game.py. Python will give a ModuleNotFoundError.

Then try appending "mylib" to sys.path at the beginning of the file game.py, before you attempt to import libmonster. Hopefully you can now successfully run python3 game.py!