How to compare Python typehints at runtime

Viewed 69

I'm playing around with trying to understand how to introspect typehints in Python, and I can't figure out how to compare hints at runtime

For example, I have two functions

def foo() -> List[str]:
    ...

def bar(values:List):
   ...

and I want to check that the output of foo() is compatible with the expected input of bar(). With some introspection I can get to the point where I can say

>>> print(return_type, expected_type)
typing.List[str] typing.List

and I want to compare these two types. Clearly a function that will accept any kind of list will accept a list of of strings, so I should be able to say that typing.List[str] is consistent with typing.List I tried

return_type == expected_type
isinstance(return_type, expected_type)
issubclass(return_type, expected_type)
return_type <= expected_type

The first two return False, the last two throw TypeErrors.

What is the correct way to compare these two type hints?

And yes, I know there are packages available to do this kind of thing, but my goal is more to understand how it works internally.

0 Answers
Related