Importing modules and packages
In the simplest case, a module is defined by a file module.py
which contains the definitions of the module contents.
Alternatively, it can be defined by a folder module
which contains a file __init__.py
which contains the definitions of the module contents. Such a folder-module is also called a package1, and the module-folder can contain other module-files or -folders, which define submodules or subpackages of the package.
For Python to be able to import a module, the module-file or top-level module-folder must be contained in one of the folders listed in sys.path
.
In the statement import module
, ‘module’ is the module’s name, which is used to find the file or folder. If the import is successful, a module object is created and assigned to the variable module
.
With the statement import module as mod
the module ‘module’ is imported, and the module object is assigned to the variable mod
.
Footnotes
This is not to be confused with a distribution package. There are also namespace packages which do not have an
__init__.py
file.↩︎