Search notes:

Python: module

A module is a file that contains statements and expressions.
This module-file must have a .py extension. The name of the file without the extension becomes the name of the module.
In order to access code in a module, it needs to be imported with the import statement.
After a module is imported, its name is added to the local scope, which can be seen by comparing the result of dir() before and after the import.
When code of the module is executed, the object __name__ is a string that evaluates to the name of the module.

Locating modules

When a Python program imports a module, the interpreter first verifies if this module belongs to the standard library and, if so, loads it.
Otherwise, it searches the module-file in the directories that are referrered to in sys.path.

Cached Python modules

When Python compiles a module, it stores the result of the compilation under a directory named __pycache__ with an extension of the Python version and .pyc.
This allows to import modules faster the second time.
Writing .pyc files can be suppressed with the command line option -B.

Module specific symbol table

Each module has its own private symbol table.
This symbol table is used in lieu of the global symbol table by the function that are defined in the module.
Thus, a function in a module cannot accidentally overwrite a global variable.

TODO

Packages

A modules with a __path__ attribute is considered a package.

See also

sys.modules is a cache for all modules that were imported.
The standard-library module importlib.
The filename (inclusive path), from which a module was loaded from, is stored in the module object's __file__ attribute.
The built-in function __import__.
Simple test cases to test the functionality of modules can be written with the module doctest.
The command line option -m runs a module as a script.

Index