Open tombulled opened 1 year ago
1. Types are the same Essentially t0 is t1
t0 is t1
class Animal: pass class Dog(Animal): pass >>> is_compatible(Animal, Animal) True >>> is_compatible(Dog, Animal) False
2. Type is a subclass Essentially issubclass(t0, t1)
issubclass(t0, t1)
class Animal: pass class Dog(Animal): pass >>> is_compatible(Animal, Animal) True >>> is_compatible(Dog, Animal) True
3. Type implements interface Uses isinstance(t0, t1)
isinstance(t0, t1)
@runtime_checkable class Processor(Protocol): def process(self, data: str, /) -> str: ... class UpperProcessor: def process(self, data: str, /) -> str: return data.upper() >>> is_compatible(UpperProcessor, Processor) True
4. Simple type annotations
>>> is_compatible(int, Any) True >>> is_compatible(list, List) True >>> is_compatible(list, Sequence) True
5. More complex type annotations
>>> is_compatible(None, Optional[str]) True >>> is_compatible(str, Union[str, int]) True >>> is_compatible(List[int], List[Any]) True >>> is_compatible(List[int], List[str]) False >>> is_compatible(Dict[str, int], Mapping[str, int]) True
Complex type annotations
>>> is_compatible(List[Dict[str, Dog]], Sequence[Mapping[str, Animal]]) True
typing_utils is a handy typing utility library
typing_utils
Recursion is your friend for this
Expose:
is_subtype
is_castable
cast
New subtype library to be created
subtype
Example: https://github.com/bojiang/typing_utils/blob/main/typing_utils/__init__.py#L400
Handy ref: https://github.com/ilevkivskyi/typing_inspect
1. Types are the same Essentially
t0 is t1
2. Type is a subclass Essentially
issubclass(t0, t1)
3. Type implements interface Uses
isinstance(t0, t1)
4. Simple type annotations
5. More complex type annotations
Complex type annotations