Content · Programming · Python

Python Lazy Imports with __lazy_modules__

A module-level __lazy_modules__ container lists fully qualified imports that should be treated as lazy, even if the source uses ordinary import statements. It supports compatible source files across versions.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

This guide explains lazy imports with __lazy_modules__ through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.

What You Will Learn


A module-level __lazy_modules__ container lists fully qualified imports that should be treated as lazy, even if the source uses ordinary import statements. It supports compatible source files across versions.

When and Why to Use It


The following example focuses on a practical use of Lazy Imports with __lazy_modules__.

Step-by-Step Example


__lazy_modules__ = ["json"]
import json

print("Ready")
print(json.dumps({"count": 3}))

Understanding the Example


On Python, the json import can be deferred because its fully qualified name appears in __lazy_modules__. Earlier Python versions ignore this special convention and import normally.

Python requirement: this feature is part of Python. It is not available in earlier interpreters; use a Python installation for this example.

Important Behavior and Edge Cases


The names must match fully qualified targets. Imports inside functions, class bodies or try blocks are not made lazy by this setting.

Try It Yourself


Add pathlib to __lazy_modules__ and compare first-access timing.

Common Beginner Mistakes


  • The names must match fully qualified targets. Imports inside functions, class bodies or try blocks are not made lazy by this setting.
  • Assuming that an import has no initialization effects or that every environment resolves modules in the same way.
  • Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.

Key Takeaways


  • A module-level __lazy_modules__ container lists fully qualified imports that should be treated as lazy, even if the source uses ordinary import statements.
  • On Python, the json import can be deferred because its fully qualified name appears in __lazy_modules__.
  • Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.
Share this resourceSend this page to someone who may find it useful.