Use isinstance for Type Checks

ID

python.type_check_isinstance

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Python

Tags

best-practice, reliability

Description

Reports comparisons of type(x) against a type (type(x) == int, type(x) is str). The Python idiom is isinstance(x, int), which also accepts subclasses; the type()-equality check rejects them, which is almost never the intended behaviour.

if type(x) == int:           # FLAW
    ...
if type(x) is list:          # FLAW
    ...

if isinstance(x, int):       # OK
    ...

Rationale

type(x) == int returns False for bool (which inherits from int), for any custom subclass of int, and for instances proxied by metaclasses. isinstance(x, int) returns True in all of those cases. Code that expects the broader behaviour — i.e. "any int-shaped value" — silently misclassifies subclass instances under type(…​) ==.

When the strict type identity is the goal (e.g. an opt-in registry that should not match subclasses), the rule’s recommended replacement is type(x) is int plus a clear comment.

Remediation

if isinstance(x, int):
    ...
if isinstance(x, (int, float)):     # multi-type check
    ...