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")
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!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
This is a bit late, but I'm pretty sure that for your first
@overload
example withdecrease()
, a better solution would be to useTypeVar
, as AnyStr does. It's sort of like generics I think. For example (I ran this through MyPy once, it seems to work):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!