Reputation: 31388
I am new to Python and I am looking to find out how Python discovers the path to modules it imports from. This would be equivalent to CLASSPATH
in Java and PERL5LIB
in Perl.
E.g. the import block in a script I am looking at looks something like this:
import os
import resource
from localnamespace.localmodule import some_class
I understand that os
and resource
are native to Python (are part of the core language API) but still the interpreter must have some pointer where to find them. As for localnamespace.localmodule
, how do we tell the interpreter where to find this module because it the directory in which this script is does not have a subdirectory named localnamespace
.
Upvotes: 0
Views: 392
Reputation: 3831
TLDR
In summary, the search process goes something like:
1) Previously imported in sys.modules
?
2) If no, can I find it in the script / interpreter directory?
3) If no, can I find it in any of the directories in the PYTHONPATH
environment variable?
4) If no, ImportError
The Longer Answer
Referring to the documentation an import
statement first looks at sys.modules
which is a dictionary of currently or recently loaded modules.
It it can't find the module there it searches through sys.meta_path
- the actual paths here vary between implementations. In general, import paths will be defined in sys.path
, which is a list of directories including those in the environment variable PYTHONPATH
.
The documentation for sys.path
describes itself as:
A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.
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.
Upvotes: 1