tombulled / needle

Dependency Injection for Python
MIT License
0 stars 0 forks source link

:sparkles: Implement Type Compatibility Checking #5

Open tombulled opened 1 year ago

tombulled commented 1 year ago

1. Types are the same Essentially 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)

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)

@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
tombulled commented 1 year ago

typing_utils is a handy typing utility library

tombulled commented 1 year ago

Recursion is your friend for this

tombulled commented 1 year ago

Expose:

tombulled commented 1 year ago

New subtype library to be created

tombulled commented 1 year ago

Example: https://github.com/bojiang/typing_utils/blob/main/typing_utils/__init__.py#L400

tombulled commented 1 year ago

Handy ref: https://github.com/ilevkivskyi/typing_inspect