Skip to content

Organize Imports: remaining gaps in string annotation handling (follow-up to #969) #993

Backlog

Description

@mcepl

Follow-up to #369 / #969, which made Organize Imports keep imports
referenced only by quoted type annotations. These remaining gaps
were found in review and deliberately left out of #969:

  1. PEP 695 type aliases lose the import. _visit_annotation
    is never reached from the TypeAlias node, so in

    from pkg1 import mod1
    
    type T = "mod1.Baz"

    from pkg1 import mod1 is removed. Same symptom as ImportOrganizer should not remove imports used in string type annotation #369, just
    in Python 3.12+ syntax.

  2. Aliased Literal / Annotated are not recognised. The
    special-casing matches only the names Literal and
    Annotated, so with

    from typing import Literal as L
    from pkg1 import mod1
    
    value: L["mod1.Baz"]

    the string is treated as a forward reference and the unused
    import is wrongly kept. Preserve imports referenced by quoted type annotations #969 pins this with an
    expectedFailure test
    (test_imports_not_used_by_aliased_literal_annotation_values).

  3. f-string annotations are matched too loosely. For
    value: f"wibble {mod1}" the literal text fragments are parsed
    as expressions as well, so an import named wibble would be
    kept. This errs on the safe side (master removed imports here
    instead) and is low priority.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions