Python: is the current directory automatically included in path?

AllTradesJack picture AllTradesJack · Jun 26, 2014 · Viewed 9.5k times · Source

Python 3.4: From reading some other SO questions it seems that if a moduleName.py file is outside of your current directory, if you want to import it you must add it to the path with sys.path.insert(0, '/path/to/application/app/folder'), otherwise an import moduelName statement results in this error:

ImportError: No module named moduleName

Does this imply that python automatically adds all other .py files in the same directory to the path? What's going on underneath the surface that allows you to import local files without appending the Python's path? And what does an __init__.py file do under the surface?

Answer

Martijn Pieters picture Martijn Pieters · Jun 26, 2014

Python adds the directory where the initial script resides as first item to sys.path:

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

So what goes on underneath the surface is that Python appends (or rather, prepends) the 'local' directory to sys.path for you.

This simply means that the directory the script lives in is the first port of call when searching for a module.

__init__.py has nothing to do with all this. __init__.py is needed to make a directory a (regular) package; any such directory that is found on the Python module search path is treated as a module.