Python defines two types of packages. regular packages and namespace packages. Regular packages are traditional packages as they existed in python3.2 and earlier. A regular package is typically implemented as a directory containing an __init__.py file. When a regular package is imported, this __init__.py file is implicitly executed, and the objects it defines are bound to names in the package's namespace. The __init__.py file can contain the same python code that any other module can contain, and python will add some additional features to the module when it is imported.
python searches a list of directories to resolve names in e.g., import statements. Because these can be any direcotry, and arbitary ones can be added by the end user, the developers have to worry about directories that happen to share a name with a valid python module, such as string in the docs example. To alleviate this, it ignores directories which do not contain a file named __init__.py, even if it is blank.
When a module named spam
is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py
in a list of directories given by the variable sys.path
. sys.path
is initialized from these locations:
-
the directory containing the input script (or the current directory).
-
PYTHONPATH
(a list of directory names, with the same syntax as the shell variablePATH
). -
the installation-dependent default.
After initialization, Python programs can modify sys.path
. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.