Skip to content

TC006 (runtime-cast-value) shouldn't trigger with annotations #20237

@Kilo59

Description

@Kilo59

Summary

TC006 forces the use of quotes strings around casts types even when from __future__ import annotations is imported.

The explanation of the rule doesn't apply when using a postponed annotations.
https://docs.astral.sh/ruff/rules/runtime-cast-value/

# runtime-cast-value (TC006)

...

It's often necessary to quote the first argument passed to `cast()`,
as type expressions can involve forward references, or references
to symbols which are only imported in `typing.TYPE_CHECKING` blocks.
This can lead to a visual inconsistency across different `cast()` calls,
where some type expressions are quoted but others are not. By enabling
this rule, you ensure that all type expressions passed to `cast()` are
quoted, enforcing stylistic consistency across all of your `cast()` calls.

In some cases where `cast()` is used in a hot loop, this rule may also
help avoid overhead from repeatedly evaluating complex type expressions at
runtime.

Important

In addition, by forcing the use of quoted strings instead of postponed annotations we >introduce a very subtle but potentially serious type-checking footgun.

That is if the TYPE_CHECKING import ever changes, the quoted string reference will silently become an Any, and neither ruff nor mypy will be able to catch it.

Full example of this issue described here 👇

Note: There may be some configurations of mypy that will catch this (if Any is banned outright for example), but most configurations likely won't catch it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionAsking for support or clarification

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions