Stewori / pytypes

Typing-toolbox for Python 3 _and_ 2.7 w.r.t. PEP 484.
Apache License 2.0
200 stars 20 forks source link

How to check if a type is a combination of some other types #42

Closed mitar closed 6 years ago

mitar commented 6 years ago

In one part of my code, where I am deciding how to convert a value to JSON, I do:

any(is_subclass(structural_type, typ) for typ in (str, int, float, bool))

What I realized is that I would be OK with all possible Union combinations of these as well. So if structural_type is Union[str, int] that should also pass this check. Do you have a suggestion how to do so, or a helper function which would already do this? So I wonder about complicated case like Union[str, Union[int, bool]] or something like that.

Stewori commented 6 years ago

Simply is_subtype(structural_type, Union[str, int, float, bool]) should do what you want if I understand your requirement correctly (otherwise, more context would be helpful).

Union[str, Union[int, bool]] is equivalent to plain Union[str, int, bool] (like Union[int] is equivalent to plainint) and I think pytypes handles this well (IIRC there are tests for it).

mitar commented 6 years ago

Oh, you are so right. Silly me. :-) Thanks!