DEV Community


Discussion on: Simple dependent types in Python

nickcrews profile image
Nick Crews

This is a bit late, but I'm pretty sure that for your first @overload example with decrease(), a better solution would be to use TypeVar, as AnyStr does. It's sort of like generics I think. For example (I ran this through MyPy once, it seems to work):

from typing import TypeVar

Decrementable = TypeVar("Decrementable", str, int)

def decrease(first: Decrementable) -> Decrementable:
    if isinstance(first, int):
        return first - 1
    return first[:-1]

two_str = "abc" + decrease("xyz")
two_ints = 5 + decrease(4)
oops1 = 5 + decrease("xyz")  # error: Unsupported operand types for + ("int" and "str")
oops2 = "abc" + decrease(4)  # error: Unsupported operand types for + ("str" and "int")
Enter fullscreen mode Exit fullscreen mode

The second @overload example would be harder to do with this pattern, but you might be able to make it work. Any thoughts? Hope this helps someone!