More Imports! - Delayed importing

7.685.25166 · active · verified Thu Apr 16

mo-imports is a Python library designed to simplify and manage complex import patterns, especially those involving cyclic dependencies. It provides mechanisms like 'expect/export' and 'delay_import' to make late importing cleaner and avoid common Python import pitfalls. The library is currently in a beta development status, with version 7.685.25166 released on June 15, 2025, and generally follows a frequent release schedule.

Common errors

Warnings

Install

Imports

Quickstart

The `mo-imports` library offers two primary patterns: `expect`/`export` for breaking cyclic dependencies and `delay_import` for deferring module loading until the first access. The `delay_import` example demonstrates how a module's content is loaded only when its components are first invoked, leading to cleaner code and potentially faster startup times if imports are expensive and not always used.

import os

# Example for breaking cyclic dependencies with expect/export
# File: foos.py
# from mo_imports import expect
# bar = expect("bar")
# def foo():
#     return bar() + " from foo"
#
# File: bars.py
# from mo_imports import export
# from foos import foo
# def bar():
#    return foo() + " from bar"
# export("bar", bar)

# Simulating the usage (actual usage requires separate files)
# To demonstrate, imagine 'foos.py' defines 'bar' as expect('bar')
# and 'bars.py' defines 'bar' and then export('bar', bar)

# Example for delayed import
# File: lazy_module.py
# def some_function():
#     return "Function from lazy_module"

# File: main_app.py
from mo_imports import delay_import

# Instead of: from lazy_module import some_function
# We use delay_import:
lazy_function = delay_import("lazy_module.some_function")

print(f"Initial state: {lazy_function}") # This is a proxy object, not the actual function yet

# The import happens when lazy_function is first 'used'
# For a function, this means when it's called.
try:
    result = lazy_function()
    print(f"Result from delayed import: {result}")
except ImportError as e:
    print(f"Caught expected ImportError: {e}")
    print("Note: For this example to run correctly, 'lazy_module.py' must exist in the Python path.")

# For demonstration, let's create a dummy lazy_module.py temporarily
with open('lazy_module.py', 'w') as f:
    f.write('def some_function():\n    return "Function from lazy_module"\n')

# Rerun the delayed import to show it working
import sys
# Remove from sys.modules to force re-import if it was loaded before
if 'lazy_module' in sys.modules:
    del sys.modules['lazy_module']

lazy_function_working = delay_import("lazy_module.some_function")
print(f"Result from delayed import after creating file: {lazy_function_working()}")

# Clean up the dummy file
os.remove('lazy_module.py')

view raw JSON →