python runtime type checking

51 views Asked by At

I would like to check the type compatibility between the output of one function and the input of another. I know mypy does static type checking but I couldn't find anything on running it from python. Here is an example of what I am trying to do:

from typing import Union, Callable
import inspect


def gt_4(num: Union[int, float]) -> bool:
    return num > 4


def add_2(num: Union[int, float]) -> float:
    return num + 2.0


def types_are_compatible(type1, type2):
    """ return True if types are compatible, else False """
    # how to do this in a clean way? 
    # some kind of MyPy API would be nice here to not reinvent the wheel

# get annotations for output of func1 and input of func2
out_annotation = inspect.signature(gt_4).return_annotation
in_annotation = inspect.signature(add_2).parameters.get('num').annotation

# check if types are compatible, 
types_are_compatible(out_annotation, in_annotation)

I found a small github project called typegaurd that seems to do something similar but I am really reluctant to use a small 3rd party library for the code I am working on. What is the cleanest way to do this? Is there anything built in to the standard library or MyPy that I can just use directly?

0

There are 0 answers