rules/python/hasattr-probe.md
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.
| 1 | -def read_stat(result: object) -> float: |
| 2 | - return result.tstats if hasattr(result, "tstats") else result.tvalues |
| 3 | +def read_stat(result: StatResult) -> float: |
| 4 | + return result.tstats |
What the rule reports
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).
How to fix it
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.