I'm using type annotatiots to do some basic type checking and automated type conversions.
As part of that, I'm looking to check if a given type should be assignable to some field of a data class, i.e. if the type is "compatible" with the type annotation on my data class.
Is there any out-of-the-box way to check if a given type is assignable to some other type? I.e.
from typing import Optional, Union, Annotated, Type
def is_assignable(from_what: Type, to_what: Type) -> bool:
// .. how?
is_assignable(int, int) // should be true
is_assignable(int, Optional[int]) should be true
is_assignable(int, Annotated[Union[str, Optional[int]], "hello world"]) // should be true
is_assignable(float, Annotated[Union[str, Optional[int]], "hello world"]) // False. Can't assign float to Annotated[Union[str, Optional[int]], "hello world"])
I could try unwrapping all the typing.* logic myself, i.e. unwrap Optional, Union, Annotated, and so forth, but that feels rather ugly (and not too maintainable, if new stuff is added in more recent python versions).