How can I check whether a lazy import has executed in Python 3.15 without triggering it with Example?

In Python 3.15, to check whether a lazy import has been executed (i.e., "reified") without triggering its execution, the correct method is to check whether the module name appears in sys.modules.

Core Method: Check sys.modules

Lazy-imported modules do not appear in sys.modules while they are not yet executed; once they are accessed and trigger execution, they are added to sys.modules, and the corresponding lazy reference is replaced with the actual module object.

Example:

import sys

# Lazy import, not yet executed
lazy import example

# Check before execution: example not in sys.modules
print( example in sys.modules)  # Output: False

# Access the module, triggers execution
print(example.value)  # Output: 42

# Check after execution: example now in sys.modules
print( example in sys.modules)  # Output: True

Why Not Use hasattr()?

The hasattr(example, "value") you mentioned will trigger the reification of the lazy import, because it requires accessing the module is attributes, which is precisely the operation that forces the lazy object to resolve into an actual module. The same applies to directly accessing any attribute of example.

Additional Diagnostic Information: sys.lazy_modules

Python 3.15 also provides sys.lazy_modules, which records the names of all modules that have been lazily imported but not yet reified. You can use it to confirm that a module is in a lazy state:

import sys
lazy import example

# Still lazy
assert example in sys.lazy_modules
assert example not in sys.modules

example.value  # Trigger execution

# Reified
assert example not in sys.lazy_modules
assert example in sys.modules

Therefore, module_name in sys.modules is a reliable, non-intrusive way to determine whether execution has occurred.

10 Views