How to type annotate a Python function that should work similar to typeguard.check_type?

30 Views Asked by At

I want implement a Python function that works like typeguard.check_type, but does additional reporting (particular to my project's needs) in case of failure.

What is the correct type annotation for a function like that?

Ideally it should at-least work with Pyright and Mypy.

I have tried the following solution:

from typing import Type, TypeVar, Any
from typeguard import check_type

T = TypeVar('T')

def my_check_type(s: Any, t: Type[T]) -> T:
    return check_type(s, t)

x = my_check_type(10, float | int)

It works for simple types with pyright, but not when the passed type is a union type. Pyright complains:

Argument of type "type[float] | type[int]" cannot be assigned to parameter
"t" of type "type[T@my_check_type]" in function "my_check_type"
(Pyright reportArgumentType)
0

There are 0 best solutions below