Skip to content

TC003’s rewritten annotations have syntax errors and type-checking problems #14538

@dscorbett

Description

@dscorbett

The fix for TC003 sometimes makes Ruff fail or introduces type-checking problems when lint.flake8-type-checking.quote-annotations = true in Ruff 0.8.0.

Here are some examples of type-checking problems. The first two make the types invalid. The rest change the types’ metadata. Metadata can be any Python expression and can be interpreted by any arbitrary tool, so Ruff should not make any assumptions about it or modify it beyond simple syntactic transformations like switching quotation marks.

$ cat tc003_1.py
from collections.abc import Sequence
from typing import Annotated
a: Sequence[tuple[()]]
b: Sequence[Annotated[int, ()]]
c: Sequence[Annotated[int, 1 + 3]]
d: Sequence[Annotated[int, ([0] + [1])[1]]]
e: Sequence[Annotated[int, list["int"]]]
f: Sequence[Annotated[int, Annotated["int", "int"]]]

$ ruff check --isolated --select TC003 --config 'lint.flake8-type-checking.quote-annotations = true' tc003_1.py --unsafe-fixes --fix
Found 1 error (1 fixed, 0 remaining).

$ cat tc003_1.py
from typing import Annotated, TYPE_CHECKING

if TYPE_CHECKING:
    from collections.abc import Sequence
a: "Sequence[tuple[]]"
b: "Sequence[Annotated[int, ]]"
c: "Sequence[Annotated[int, 1 | 3]]"
d: "Sequence[Annotated[int, [0] + [1][1]]]"
e: "Sequence[Annotated[int, list[int]]]"
f: "Sequence[Annotated[int, Annotated[int, 'int']]]"

$ mypy tc003_1.py
tc003_1.py:5: error: Invalid type comment or annotation  [valid-type]
tc003_1.py:6: error: Annotated[...] must have exactly one type argument and at least one annotation  [valid-type]
Found 2 errors in 1 file (checked 1 source file)

Here is an example of a failure.

$ cat tc003_2.py
from collections.abc import Sequence
from typing import Annotated
x: Sequence[Annotated[int, "x"[0]]]

$ ruff check --isolated --select TC003 --config 'lint.flake8-type-checking.quote-annotations = true' tc003_2.py --unsafe-fixes --diff

error: Fix introduced a syntax error. Reverting all changes.

This indicates a bug in Ruff. If you could open an issue at:

    https://github.com/astral-sh/ruff/issues/new?title=%5BFix%20error%5D

...quoting the contents of `tc003_2.py`, the rule codes TC003, along with the `pyproject.toml` settings and executed command, we'd be very appreciative!

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingfixesRelated to suggested fixes for violationshelp wantedContributions especially welcome

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions