Skip to content

python/hasattr-probe

Pack Severity Fix Versions
Python warning none, edit by hand All versions

Probing objects at runtime with hasattr(obj, "name") hides attribute contracts behind string duck-typing and keeps legacy attribute fallbacks alive where static search and type checkers cannot verify them. Declare a typing.Protocol or accept one canonical typed interface instead.

def read_stat(result: object) -> float:
return result.tstats if hasattr(result, "tstats") else result.tvalues
def read_stat(result: StatResult) -> float:
return result.tstats

The rule reports two forms of hasattr probing:

  • A ternary dual-attribute fallback (obj.new if hasattr(obj, "new") else obj.old) anywhere, including tests.
  • Any hasattr(obj, "name") call with a string literal attribute name in production modules.

The rule leaves alone standalone hasattr checks inside test files (tests/**, test_*.py, *_test.py, conftest.py).

xpd has no automatic fix, so make the change by hand.

Remove legacy dual-attribute fallbacks and read the single canonical attribute. When genuinely polymorphic objects need runtime capability checks, define a @runtime_checkable typing.Protocol and check isinstance(obj, MyProtocol) so both static search and the type checker see the contract.

Branching on hasattr($OBJ, $STR) between two attributes keeps a legacy attribute alias alive. Read one canonical attribute name.

See all rules in the Python pack.