
Understanding Modules
When you exit the Python interpreter and restart it, any definitions you made (functions and variables) are lost. For longer programs, it’s better to use a text editor to prepare your code in a file and run that file as input to the interpreter. This is called creating a script. As programs grow larger, you might want to split them into multiple files for easier maintenance, or reuse handy functions across different programs without copying them each time.
Python supports this through modules – files containing Python definitions and statements that can be imported into other modules or the main module. The module name is the file name with a .py
extension. Inside a module, its name (as a string) is available as the global variable __name__
.
Here’s an example module named fibo.py
:
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
To use this module:
import fibo
This adds the module name fibo
to the current namespace, letting you access its functions:
fibo.fib(1000)
fibo.fib2(100)
fibo.__name__
For frequently used functions, you can assign them to local names:
fib = fibo.fib
fib(500)
Module Details
Modules can contain both executable statements and function definitions. These statements initialize the module and run only the first time the module is imported. Each module has its own private namespace, preventing accidental clashes with global variables in other modules.
You can import specific names directly:
from fibo import fib, fib2
fib(500)
Or import all names (not generally recommended):
from fibo import *
fib(500)
You can also rename imports:
import fibo as fib
fib.fib(500)
from fibo import fib as fibonacci
fibonacci(500)
Note: Modules are imported only once per interpreter session. To reload a modified module, use importlib.reload()
.
Executing Modules as Scripts
When you run a module directly with python fibo.py <arguments>
, its code executes with __name__
set to "__main__"
. You can make a module work both as an importable module and executable script:
if __name__ == "__main__":
import sys
fib(int(sys.argv[1]))
Module Search Path
When importing a module, Python searches:
- Built-in modules
- The
sys.path
list, which includes:
- The directory containing the input script
PYTHONPATH
environment variable directories- Installation-dependent default paths
Compiled Python Files
Python caches compiled modules in __pycache__
as .pyc
files to speed up loading. These are platform-independent and automatically regenerated when the source changes.
Standard Modules
Python includes many standard modules described in the Library Reference. The sys
module is particularly important, providing access to interpreter variables like sys.path
(module search path) and sys.ps1
/sys.ps2
(prompt strings).
The dir() Function
The dir()
function lists names defined by a module:
import fibo, sys
dir(fibo)
dir(sys)
Without arguments, dir()
lists currently defined names. For built-in names, use dir(builtins)
.
Packages
Packages structure Python’s module namespace using dotted names (e.g., A.B
). They help avoid naming conflicts between modules.
A package directory typically contains:
__init__.py
(identifies the directory as a package)- Submodules and subpackages
Example package structure:
sound/ # Top-level package
__init__.py # Initialize package
formats/ # Subpackage
__init__.py
wavread.py
...
effects/ # Subpackage
__init__.py
echo.py
...
Importing from Packages
You can import in several ways:
import sound.effects.echo # Full path
sound.effects.echo.echofilter(...)
from sound.effects import echo # Shorter reference
echo.echofilter(...)
from sound.effects.echo import echofilter # Direct import
echofilter(...)
Importing * from Packages
The __all__
list in __init__.py
controls what gets imported with from package import *
:
__all__ = ["echo", "surround", "reverse"]
Relative Imports
Within packages, you can use relative imports:
from . import echo # Current package
from .. import formats # Parent package
from ..filters import equalizer
Packages in Multiple Directories
Packages can use the __path__
attribute to support multiple directory locations, though this is an advanced feature.