Quantcast
Channel: User Sourav Kannantha B - Stack Overflow
Viewing all articles
Browse latest Browse all 60

Answer by Sourav Kannantha B for Why does Python not allow Generics with isinstance checks?

$
0
0

As mentioned in this answer, unfortunately it is not possible to type check generics at runtime. But if your use case to assert types for type checkers like my in case, this is what I came up with:

def istype[T](__obj: Any, __typ: type[T]) -> TypeGuard[T]:"""Return typeguard assuming object is an instance of given type"""    return True

Note that this doesn't do any type checking at all actually. But suppose an object has type Any and you want to tell type-checker that it's type is MyType instead then you can use it like this:

x = some_external_func()  # now type-checker treats x as having type Anyassert istype(x, MyType)  # now onwards type-checker will treat x as having type MyType

This is similar to typing.cast but with a broader area of influence rather than just the current expression.


Viewing all articles
Browse latest Browse all 60

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>