Skip to content

PY-TYPE0005 · repeated_cast_patterns

Count casts and flag structurally repeated cast patterns.

This is a deterministic rule for python. Read its implementation.

Group every call resolved to typing.cast or typing_extensions.cast by target type and normalized producer pattern. Subscript keys and literal values are ignored, while container names, attributes, and callees remain part of the pattern. A group with at least minimum_repetitions occurrences is an anti-pattern finding because repetition usually means the same missing type contract is being overridden at several call sites. The value counts casts in qualifying repeated patterns, so an isolated cast cannot fail without a finding.

Each finding reports the repeated target and producer pattern, occurrence count, affected file count, representative location, and up to 32 exact source locations. The suggested repair points toward one boundary validation, a typed model or TypedDict, a type guard, a Protocol, a generic, or an overload. Isolated casts remain in the provider fact without becoming a finding. The value is the number of casts inside repeated patterns rather than the number of patterns.

A cast can be appropriate at an untyped or incorrectly typed third-party boundary because cast is a static assertion and performs no runtime validation. Even boundary casts become a finding when the same assertion is repeated. Validate or wrap that boundary once instead.

Bad

Three calls such as `cast(str, row["id"])`, `cast(str, row["name"])`, and
`cast(str, row["owner"])` form the pattern `str` from `subscript row`. Parse `row` once as
a typed record instead of asserting every field independently.
Good

One cast around the result of an untyped extension API is counted but not flagged. Replacing repeated casts with Record.model_validate(raw) creates one runtime boundary and typed uses after it.

  • Cites “Python typing specification”, Type checker directives, cast(). Open reference
  • Cites “Mypy documentation”, redundant-cast. Open reference
  • Cites “Pyright documentation”, configuration, reportUnnecessaryCast. Open reference