Python Modules
Clear, original guide to python modules: how to create, import (import, from, as), use __name__ == '__main__', sys.path/PYTHONPATH, module vs package, listing modules, and best practices.
Drake Nguyen
Founder · System Architect
What are Python modules?
A python module is a single .py file that groups related variables, functions, and classes so you can reuse and organize code. Using modules makes projects easier to manage, reduces duplication, and creates clear namespaces for imports. The term "python modules" also covers built-in modules and third-party modules available in the standard library and site-packages.
Create and use a python module (python module example)
To create a module, save Python code in a file. For example, create a file named numbers_util.py:
# numbers_util.py
def forward(n):
"""Yield numbers 1..n"""
for i in range(1, n + 1):
print(i)
def backward(n):
"""Yield numbers n..1"""
for i in range(n, 0, -1):
print(i)
# protect side effects when the module is executed directly
if __name__ == '__main__':
forward(5)
This demonstrates both module contents and the common pattern python __name__ == '__main__' to make behavior different when a file is run as a script versus imported as a module.
How to import a module in python
Basic importing uses the import statement. After creating numbers_util.py, import it from the same directory:
import numbers_util
numbers_util.forward(3)
You can rename an imported module with as for convenience:
import numbers_util as nu
nu.backward(4)
To import specific names into the current namespace, use from import:
from numbers_util import forward
forward(2)
Avoid from module import * since it pollutes the namespace and makes code harder to read and maintain. Use explicit imports for clarity — this is one of the best practices for importing modules in python.
Importing from another directory (python sys.path append example)
When Python imports a module, it searches the module search path. The search path includes the current directory, entries from PYTHONPATH, and locations such as site-packages. If you get ModuleNotFoundError, the module file is not on the search path. You can inspect the search path with sys.path and temporarily extend it:
import sys
sys.path.append('/home/user/my-python-modules')
import some_module_from_other_dir
Using PYTHONPATH or installing the package into a virtual environment (site-packages) is preferable for persistent projects. For production code, prefer proper packaging or relative/absolute imports inside packages rather than ad-hoc sys.path changes.
Python modules vs packages
A python module is one .py file. A package is a directory that groups modules and may include an __init__.py file to declare the package. Packages allow hierarchical namespaces and relative imports inside a project.
Example package layout:
myproject/
mypackage/
__init__.py
core.py
utils.py
Import with absolute or relative imports, for example:
from mypackage import core
from .utils import helper_function # relative import within a package
For dynamic importing, use importlib. For third-party modules, use pip to install into a virtual environment so they appear in site-packages and are discoverable by the python module search path.
How to list installed and available modules
To see modules available in the current interpreter session, use the interactive helper:
help('modules')
To programmatically list importable modules:
import pkgutil
sorted_names = sorted([m.name for m in pkgutil.iter_modules()])
print(sorted_names[:20])
Inspecting sys.modules reveals modules already loaded into memory. The official Python Module Index (the standard library index) lists python standard library modules and the built-in modules in python.
Common pitfalls and best practices
- Prefer explicit imports (e.g.,
from package import name) over wildcard imports. - Keep modules small and focused to make unit testing and reuse easier.
- Avoid running heavy computation at import time; prefer functions or use the
__name__ == '__main__'guard for script behavior. - Use virtual environments and install dependencies with
pip, so modules reside in site-packages and Netalith not require manual path manipulation. - Use descriptive module filenames (single word, lowercase) and avoid names that shadow standard library modules.
- When importing from other directories, favor packaging the code or setting
PYTHONPATHinstead of modifyingsys.pathat runtime. - Use
__all__in modules to control whatfrom module import *would export (but still avoid wildcard imports).
Quick FAQ
How Netalith I create a module in python?
Create a .py file containing functions/classes and import it from other scripts. Use the __name__ == '__main__' pattern to keep import-time behavior minimal.
How can I import a module from a different directory?
Either add the directory to PYTHONPATH, install the module into your environment, or temporarily append the path to sys.path. For maintainable projects, package the module and install it into a virtual environment.
Where can I find a python module list?
Use help('modules') in the interpreter to see modules available to that Python installation. The official Python Module Index documents the standard library modules.
Tip: If you see
ModuleNotFoundError, checksys.path, confirm the file name ends with.py, and avoid naming your module the same as a standard library module.