Skip to content

TC003: Allow TYPE_CHECKING = False #16176

@hugovk

Description

@hugovk

Description

TC003:

Checks for standard library imports that are only used for type annotations, but aren't defined in a type-checking block.

https://docs.astral.sh/ruff/rules/typing-only-standard-library-import/#typing-only-standard-library-import-tc003

TYPE_CHECKING = False

from __future__ import annotations

TYPE_CHECKING = False
if TYPE_CHECKING:
    import os


def thing(locale: os.PathLike[str]) -> None: ...

Ruff doesn't allow it:

❯ ruff --version
ruff 0.9.6
❯ ruff check --select TC --isolated 1.py
1.py:5:12: TC003 Move standard library import `os` into a type-checking block
  |
3 | TYPE_CHECKING = False
4 | if TYPE_CHECKING:
5 |     import os
  |            ^^ TC003
  |
  = help: Move into type-checking block

Found 1 error.

But upstream https://pypi.org/project/flake8-type-checking/ does:

❯ flake8 --version
7.1.1 (flake8-2020: 1.8.1, flake8-implicit-str-concat: 0.5.0, flake8-type-checking: 3.0.0, mccabe: 0.7.0, pycodestyle: 2.12.1, pyflakes: 3.2.0) CPython 3.13.2 on Darwin
❯ flake8 1.py
❯ 

from typing import TYPE_CHECKING

Both are fine with this:

from __future__ import annotations

from typing import TYPE_CHECKING
if TYPE_CHECKING:
    import os
❯ ruff check --select TC --isolated 1.py
All checks passed!

❯ flake8 1.py --statistics
❯ 

But the whole point of this typing-only-standard-library-import TC003 check is to avoid imports that are only needed for type checking:

Unused imports add a performance overhead at runtime, and risk creating import cycles. If an import is only used in typing-only contexts, it can instead be imported conditionally under an if TYPE_CHECKING: block to minimize runtime overhead.

See also:

Which look like it should have fixed it in 0.9.5, but I can repro in 0.9.4-0.9.6.

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