4

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Fergal
  • 494
  • 3
  • 12
  • Have you seen https://stackoverflow.com/questions/45658550/compare-types-from-python-typing? – funnydman Aug 12 '22 at 15:56
  • 1
    This one too: https://stackoverflow.com/questions/50563546/validating-detailed-types-in-python-dataclasses – Jab Aug 12 '22 at 15:56
  • 1
    `typing.get_origin(typing.get_type_hints(foo)["return"]) == typing.get_origin(typing.get_type_hints(bar)["values"])` – d.b Aug 12 '22 at 16:02
  • I wasn't aware of get_origin, but if I tried to compare List[str] with List[int] using get_origin wouldn't that mistakenly say the two datatypes are compatible? – Fergal Aug 12 '22 at 17:30

0 Answers0