Ferus
Ferus

Reputation: 1118

Check parameter types dynamically in python and typings

I have a class with a sort of pipeline structure and I'd like to have a function that checks that the steps in the pipeline are compatible. Thus I want to loop through all steps and check that the input is compatible with the output of the previous step given the type hints. Now, this is done by extracting the types from the signatures and then comparing the types. The problem is, how do I compare the types? Seems I can't find any way of doing it for some reason. For instance Any can't be used at all with issubclass. I use python 3.8. I would like for it to work for instances such as:

is_compatible(List, Any) # => True
is_compatible(List[np.ndarray], List[Union[np.ndarray, list]]) # => True
is_compatible(List[str], List[int]) # => False
# etc.

Upvotes: 1

Views: 70

Answers (1)

leaf_soba
leaf_soba

Reputation: 2518

example

    from typing_utils import issubtype
    issubtype(typing.List, typing.Any) == True
    issubtype(list, list) == True
    issubtype(list, typing.List) == True
    issubtype(list, typing.List[int]) == False

Upvotes: 2

Related Questions