Narrowing with isinstance and possibly subscripted generic

The key difficulty here is that:

# TypeError: Subscripted generics cannot be used with class and instance checks

If the only subscripted generics you want to support are garden-variety collection types like List[MyClass] or Set[MyClass] then you might consider using isassignable from trycast or similar enhanced isinstance functions in other libraries.

In the case of the trycast library in particular, I know that “User-defined generic types” (which would also support custom subscripted generics beyond the usual collection types) is on the roadmap.

1 Like