loader
In Python, a loader is responsible for loading a module or package into a Python runtime environment. Loaders are a crucial part of Python’s import system, as they define how to fetch and execute the code of a module or package.
When you import a module, a finder first locates it and returns a module spec. Python then uses the loader named by that spec to load the module’s code. The loader then executes that code in the module’s namespace, populating it so the module is ready for use. Loaders can vary based on the source of the module, such as file systems, zip files, or even network locations.
Example
Here’s an example of how to create a custom loader:
loader.py
import importlib.util
import importlib.abc
import sys
class CustomLoader(importlib.abc.Loader):
def create_module(self, spec):
return None
def exec_module(self, module):
print(f"Loading module: {module.__name__}")
module.__dict__["greet"] = lambda: "Hello from the custom loader!"
spec = importlib.util.spec_from_loader("module", CustomLoader())
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Usage
print(module.greet()) # Output: Hello from the custom loader!
This example demonstrates how to create a custom loader that modifies the module’s namespace to include a new function called greet().
Related Resources
Tutorial
Python import: Advanced Techniques and Tips
The Python import system is as powerful as it is useful. In this in-depth tutorial, you'll learn how to harness this power to improve the structure and maintainability of your code.
For additional information on related topics, take a look at the following resources:
- Absolute vs Relative Imports in Python (Tutorial)
- Python Zip Imports: Distribute Modules and Packages Quickly (Tutorial)
- Advanced Python import Techniques (Course)
- Python import: Advanced Techniques and Tips (Quiz)
- Absolute vs Relative Imports in Python (Course)
- Absolute vs Relative Imports in Python (Quiz)
By Leodanis Pozo Ramos • Updated June 1, 2026