Skip to content
Sarj Code Standards

no-contradictory-type-guard

Type guards must agree with the predicate they return.

Why

Callers trust a guard's declared target. An incompatible primitive test or an unconditional result can narrow a value incorrectly. TypeIs can also exclude the target incorrectly in the false branch.

Fix

Align the declared target and runtime test. For an intentional partial predicate, TypeGuard may narrow only the true branch; TypeIs must recognize every target value admitted by its input. Review callers before changing the narrowing contract.

Examples

Before — flagged An integer test does not prove a string
app/guards.py
from typing import TypeGuard
def is_text(value: object) -> TypeGuard[str]:
return isinstance(value, int)
After — preferred Recognize the primitive promised to callers
app/guards.py
from typing import TypeGuard
def is_text(value: object) -> TypeGuard[str]:
return isinstance(value, str)
Before — flagged A constant result does not prove a primitive type
app/guards.py
from typing import TypeGuard
def is_text(value: object) -> TypeGuard[str]:
return True
After — preferred TypeGuard can intentionally recognize no inputs
app/guards.py
from typing import TypeGuard
def is_text(value: object) -> TypeGuard[str]:
return False
Before — flagged An unconditional result does not identify a user
app/guards.py
from typing import TypeIs
class User:
pass
def is_user(value: object) -> TypeIs[User]:
return True
After — preferred Check the value's class before narrowing
app/guards.py
from typing import TypeIs
class User:
pass
def is_user(value: object) -> TypeIs[User]:
return isinstance(value, User)