This rule raises an issue on an import or from … import statement in the body of a function or method, including nested
and async functions, when all the Python versions targeted by the project are 3.15 or later, unless one of the exceptions below applies.
lazy import is a syntax error in earlier versions.
Importing a module inside a function is a common workaround to avoid paying for an expensive import when a module is loaded, or to break an import cycle. The module is only loaded when the function first runs.
This workaround has drawbacks:
import statement runs again on every call.Since Python 3.15 (PEP 810), a lazy import at module level defers loading in a similar way. The name is bound to a lightweight proxy,
and the module is loaded on its first use. The import stays at the top of the file, together with the other dependencies of the module.
No issue is raised when moving the import to a module-level lazy import would change the behavior of the code:
try statement, in any of its clauses, or inside a with statement. A lazy import
runs the import when the name is first used, so the exception handling or the context set up by these statements, such as suppressed exceptions or
warnings, a modified sys.path, or patched modules, would no longer apply to it.lazy import would never load the module, because the name is never used.open in from gzip import open, or is
bound to a different module in another function, for example import numpy as xp in one function and import cupy as xp in
another.@ray.remote, @dask.delayed,
PySpark udf or pandas_udf, or Airflow @task.virtualenv or @task.external_python, or a method of
a class decorated with @ray.remote. A module-level lazy import is not available in that process, and it cannot be
serialized with the function.Move the import to the module level and prefix it with the lazy keyword.
Keep in mind that this changes when and how the import happens:
sys.path) at that time.sys.modules, no longer sees the change.from module import * includes it unless
__all__ is defined.
def to_json(data):
import json # Noncompliant
return json.dumps(data)
lazy import json
def to_json(data):
return json.dumps(data)
The same applies to imports used to break an import cycle:
def find_owner(item):
from .users import User # Noncompliant
return User.get(item.owner_id)
lazy from .users import User
def find_owner(item):
return User.get(item.owner_id)