What is a Module?
A module is a file containing Python definitions and statements. The filename is the module name with the suffix.py added.
Creating a Module
Create a file calledfibo.py:
fibo.py
Using a Module
Import and use the module:More on Modules
Modules can contain executable statements as well as function definitions. These statements initialize the module and run only the first time the module is imported.Import Variants
Import specific names:Executing Modules as Scripts
Add this code to make your module executable:fibo.py
This pattern is commonly used to provide a convenient interface for testing purposes or to make modules usable both as scripts and importable libraries.
The Module Search Path
When importing a module namedspam, Python searches:
- Built-in modules (listed in
sys.builtin_module_names) - Directories in
sys.path, which includes:- The directory containing the input script (or current directory)
PYTHONPATH(environment variable)- Installation-dependent defaults (including
site-packages)
sys.path at runtime:
Compiled Python Files
Python caches compiled modules in the__pycache__ directory as module.{version}.pyc files to speed up loading.
Key points:
- Python checks if the source is newer than the compiled version
.pycfiles are platform-independent- Programs don’t run faster from
.pycfiles; they just load faster
Standard Modules
Python comes with a library of standard modules. For example, thesys module:
The dir() Function
Find out which names a module defines:Packages
Packages are a way of structuring Python’s module namespace using “dotted module names”.Package Structure Example
Importing from Packages
Import individual modules:Importing * From a Package
To control whatfrom package import * imports, define __all__ in __init__.py:
sound/effects/__init__.py
Intra-package References
Use relative imports within packages:.refers to the current package..refers to the parent package
Relative imports are based on the current module’s name. The main module must always use absolute imports.
Packages in Multiple Directories
Packages support the__path__ attribute, which can be modified to extend the set of modules found in a package. This feature is rarely needed but can be used to extend packages.
