Skip to content

python/defensive-type-coercion

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

Coercing a parameter in place with if isinstance(param, ...): param = ... lets two representations of the same concept spread through internal functions. Convert once at the system boundary and accept one canonical type everywhere inside.

def read_invoice(path: str | Path) -> str:
if isinstance(path, str):
path = Path(path)
def read_invoice(path: Path) -> str:
return path.read_text()

The rule reports a function that checks isinstance(param, ...) on one of its own parameters and immediately reassigns param in place using a constructor or conversion call (if isinstance(param, str): param = Path(param) or param = Path(param) if isinstance(param, str) else param).

The rule leaves alone the cases in the list:

  • Type-narrowing dispatch across sum types (if isinstance(node, Leaf): ... elif isinstance(node, Branch): ...).
  • Validation guards (if not isinstance(x, int): raise TypeError(...)).
  • Boundary parser functions that take raw input and return a new typed object without mutating the parameter in place.

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

Narrow the function signature to the single canonical type, convert raw strings or dicts once at the outermost entry point, and delete the in-place isinstance coercion.

Coercing parameter $PARAM in place with isinstance lets two representations leak through internal code. Normalize to one type once at the boundary and accept only that type here.

See all rules in the Python pack.