Skip to content

Support and lints for lazy imports in Python 3.15+ #21305

Closed

Description

@dylwil3

This issue tracks support for lazy imports in Ruff.

Python 3.15 introduced PEP 810 - Explicit lazy imports. We have done the following:

  • Update the parser
  • Update the formatter
  • Update the semantic model (though according to this subheading these will be treated the same as ordinary imports for our purposes)

But we may also want to consider some lints. For example:

  1. ✅ Sorting these imports - Retain lazy keyword when sorting imports #23762
  2. ✅ Adjust the fixes in flake8-type-checking to suggest that typing-only imports be lazily imported rather than gated behind if TYPE_CHECKING, as per this use-case in the PEP - [flake8-type-checking] Prefer lazy imports over TYPE_CHECKING on 3.15+ (TC001, TC002, TC003) #28541
  3. Relatedly - replacing existing if TYPE_CHECKING: ... imports with lazy imports.
  4. Suggesting lazy imports any time we see an import not at the beginning of the file. (Developers sometimes approximate lazy imports these days by importing in the body of a function, for example.)
  5. ✅ Enforce lazy imports always (or for configurable set of modules) - Add a rule to enforce lazy imports #23777
  6. ✅ Conversely, removing lazy if we can guarantee that the import will be evaluated (e.g. by a top-level statement in the module) - Add a rule to flag lazy imports that are eagerly evaluated #25016

Activity

  1. added
    python315
    on Nov 6, 2025
  2. Avasam commented on Nov 10, 2025

    @Avasam
    Contributor
    1. Suggesting lazy imports any time we see an import not at the beginning of the file. (Developers sometimes approximate lazy imports these days by importing in the body of a function, for example.)
    2. More aggressive/opinionated lints - e.g. "make all imports lazy", with an unsafe autofix.

    Somewhere in between, less aggressive: Suggesting lazy imports whenever a symbol isn't obviously used at the module root level (still imperfect, but less false-positives than "make all imports lazy")

    In other words: "5. Make all imports lazy, except when detected to be used at module root".

    Further refinement with code analysis could try to follow function calls, but that seems niche.

  3. brettcannon commented on Feb 20, 2026

    @brettcannon
    Contributor

    This is now in main.

  4. tobiasdiez commented on Feb 20, 2026

    @tobiasdiez

    @brettcannon This is awesome. Just for clarification, did only the 'basic' support landed (the first 3 points in the issue description) or are also the other ones already done? In particular, I'm curious about what ordering of the imports you decided to implement ("Sorting these imports (this requires a few design decisions)").

  5. ntBre commented on Feb 20, 2026

    @ntBre
    Contributor

    I think Brett meant that this landed in CPython! We haven't added this support to Ruff yet, as far as I know.

  6. brettcannon commented on Feb 20, 2026

    @brettcannon
    Contributor

    I think Brett meant that this landed in CPython!

    Correct! Sorry about the ambiguous wording. 😅

  7. hugovk commented on Feb 25, 2026

    @hugovk
    Contributor

    From the PEP:

    Compatibility for library authors was also a key concern. Many maintainers need a migration path that allows them to support both new and old versions of Python at once. For this reason, the proposal includes the __lazy_modules__ global as a transitional mechanism. A module can declare which imports should be treated as lazy (by listing the module names as strings), and on Python 3.15 or later those imports will become lazy automatically, as if they were imported with the lazy keyword. On earlier versions the declaration is ignored, leaving imports eager. This gives authors a practical bridge until they can rely on the keyword as the canonical syntax.

    It would be useful to also sort __lazy_modules__. Two options:

    • Alphabetical
    • Follow the isort settings, for example: stdlib, third-party, local

    And the Steering Council's acceptance said:

    We agree that the PEP should take no position on any style recommendations for sorting lazy imports. While we generally like the idea of grouping lazy imports together, let’s leave that up to the linters and auto-formatters to decide the details.

    See also PyCQA/isort#2462.

  8. charliermarsh commented on Mar 9, 2026

    @charliermarsh
    Member

    We now have support for this in the parser, and a rule to enforce lazy imports: #23777

  9. Avasam commented on Mar 9, 2026

    @Avasam
    Contributor

    Can I require lazy imports for all modules except specific ones I know have side effects ?
    Same reason pywin32 would use allowed-unused-imports

    With banned-eager-imports (if comparable with the documentation from https://docs.astral.sh/ruff/settings/#lint_flake8-tidy-imports_banned-module-level-imports) I'd have to list every possible import in existence except the ones I know have side effects.

  10. charliermarsh commented on Mar 9, 2026

    @charliermarsh
    Member

    That seems reasonable to support.

  11. DanielNoord commented on Mar 14, 2026

    @DanielNoord
    Contributor

    Hey, isort maintainer checking in here!
    I don't think we'll (ever) support enforcing lazy imports as that feels more like a linting rule (and we're a bit short staffed to implement new features anyway).
    Just wanted to discuss/check how you are planning on sorting lazy imports. Is the idea to apply the same sorting rules to them as for the other import statements? Or do you have different plans.

    I think it would be helpful for the community at large if (default) behaviour of isort matches ruff and (vice-versa although I obviously can't force you to 😄).
    Feel free to chime in our repository as well (PyCQA/isort#2462).

  12. dylwil3 commented on Mar 14, 2026

    @dylwil3
    CollaboratorAuthor

    Just wanted to discuss/check how you are planning on sorting lazy imports. Is the idea to apply the same sorting rules to them as for the other import statements? Or do you have different plans.

    At the moment we do this: #23762 (comment)

    i.e. group eager before lazy within each section.

    But we're open to other possibilities!

  13. 7 remaining items

  14. chet-manley commented on May 14, 2026

    @chet-manley
  15. ntBre commented on May 14, 2026

    @ntBre
  16. added
    rule
    on Sep 4, 2026
  17. DanielNoord commented on Oct 5, 2026

    @DanielNoord
    Contributor

    Hey, checking in from PyCQA/isort#2462 (comment)

    Do you have an opinion on sorting __lazy_modules__? I am personally leaning towards just doing those alphabetically and not bothering with the regular sorting we do for imports. Does ruff have an opinion on this?

  18. ntBre commented on Oct 5, 2026

    @ntBre
    Contributor

    Alphabetical sounds reasonable to me, personally! We have a couple of other sorting rules that also use "isort-style" sorts like unsorted-dunder-all (RUF022), which uses a "natural sort" grouped by type, and unsorted-dunder-slots (RUF023), which just uses a natural sort. We could reuse that here too.

  19. hugovk commented on Oct 5, 2026

    @hugovk
    Contributor

    Keep in mind that __lazy_modules__ can be any container, not just a list:

    A container (an object implementing __contains__()) of fully qualified module name strings.

    docs.python.org/3.15/reference/datamodel.html#module.__lazy_modules__

    (And looks like a set is often the quickest: henryiii/flake8-lazy#50.)

  20. Avasam commented on Oct 5, 2026

    @Avasam
    Contributor

    flake8-lazy can also be a reference implementation for __lazy_modules__ sorting.

  21. DanielNoord commented on Oct 5, 2026

    @DanielNoord
    Contributor

    LZY201: lazy_modules list is not sorted (string entries first, relative f"{spec.parent}..." entries last, as an editor line sort produces)

    This seems like a good enough heuristic.

    __lazy_modules__ = [
        "contextlib",
        "difflib",
        "os",
        f"{__spec__.parent}._compat",
        f"{__spec__.parent}._util",
    ]

    Looks pretty reasonable to me. Thanks all!

  22. MichaReiser commented on Oct 19, 2026

    @MichaReiser
    Member

    Should we close this issue, given that general support has now been released, and create new sub issues for what's still missing?

  23. ntBre commented on Oct 19, 2026

    @ntBre
    Contributor

    Sure, I can reopen #29378 to track point 3 and open a new issue for point 4.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    python315rule

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions