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.

Why is this an issue?

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:

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.

Exceptions

No issue is raised when moving the import to a module-level lazy import would change the behavior of the code:

How to fix it

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:

Code examples

Noncompliant code example

def to_json(data):
    import json  # Noncompliant
    return json.dumps(data)

Compliant solution

lazy import json

def to_json(data):
    return json.dumps(data)

The same applies to imports used to break an import cycle:

Noncompliant code example

def find_owner(item):
    from .users import User  # Noncompliant
    return User.get(item.owner_id)

Compliant solution

lazy from .users import User

def find_owner(item):
    return User.get(item.owner_id)

Resources

Documentation