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.