typing.get_type_hints function for this use case, see https://docs.python.org/3.9/library/typ
You can use the typeguard module which can be installed with pip. It provides you with a function check_argument_types or a function decorator @typechecked. which should do your runtime type checking for you: https://github.com/agronholm/typeguard
from typing import Union
from typeguard import check_argument_types, typechecked
def check_and_do_stuff(a: Union[str, int]) -> None:
check_argument_types()
# do stuff ...
@typechecked
def check_decorator(a: Union[str, int]) -> None:
# do stuff ...
check_and_do_stuff("hello")
check_and_do_stuff(42)
check_and_do_stuff(3.14) # raises TypeError
If you want to check a type of a single variable for a different reason, you can use typeguard's check_type function directly:
from typing import Union
from typeguard import check_type
MyType = Union[str, int]
check_type("arg", "string", MyType, None) # OK
check_type("arg", 42, MyType, None) # OK
check_type("arg", 3.5, MyType, None) # raises TypeError
The "arg" and None arguments are unused in this example.
Note that the check_type function is not documented as a public function of this module so its API may be subject to change.