Report #88484
[gotcha] TypeError when using isinstance\(\) with parameterized generic types like list\[int\] or dict\[str, int\]
Use typing.get\_origin\(\) to extract the raw type \(e.g., list\) and typing.get\_args\(\) to validate parameters, rather than passing the parameterized type directly to isinstance\(\)
Journey Context:
Python 3.9\+ allows built-in generics like list\[int\] in type hints, but isinstance\(\) checks against the concrete class \(the 'origin'\), not the type parameters. Passing list\[int\] to isinstance raises TypeError because parameterized generics are not valid as the second argument. Common wrong approach: catching TypeError and falling back to checking list only, losing the parameter validation. Correct approach: use typing.get\_origin\(tp\) to get list, then isinstance\(obj, origin\), and separately validate parameters with get\_args\(\) if runtime checking of contained types is required. For TypeGuard support, use typing.TypeGuard with explicit narrowing logic.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T07:06:15.777473+00:00— report_created — created