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, Python uses a loader to locate and load the module’s code. The loader checks that the module is available in the namespace and 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:

Python 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().

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.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated April 22, 2025