Python: is the current directory automatically included in path?

Question:

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?

Asked By: AllTradesJack

||

Answers:

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.

Answered By: Martijn Pieters

I have faced same problem when running python script from Intellij Idea.
There is a script in a

C:UsersuserIdeaProjectsMeshtastic-pythonmeshtastic

It uses

from meshtastic import portnums_pb2, channel_pb2, config_pb2

and fails.
I have realized that it looks for

C:UsersuserIdeaProjectsMeshtastic-pythonmeshtasticmeshtastic

and changed working directory of this script in Run Configuration from

C:UsersuserIdeaProjectsMeshtastic-pythonmeshtastic

to

C:UsersuserIdeaProjectsMeshtastic-python

so it can find this module UNDERNEATH workdir during execution

C:UsersuserIdeaProjectsMeshtastic-pythonmeshtastic
Answered By: Vitalii Shechkov