You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
TypeError: unsupported operand type(s) for +: 'int' and 'str'
context: I was introducing someone to mypy and used the example above as something that mypy should flag, but turns out it wasn't being flagged so logging here.
It's easy to put a TypeVar bound on the first overload, but sum() doesn't work for strings even if you define start="". It intentionally works with everything except strings.
>>> sum("asd", start="")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]
It's easy to put a TypeVar bound on the first overload
Even that's actually a little tricky, because you get into the question of what is a number.
For example, this works fine, even though there's not really anything that these classes all have in common either from a nominal or structural point of view:
We could at least bound the TypeVar to a Protocol defining __add__. That wouldn't help with Alex's mixed numeric types, but it would help type checkers catch plausible mistakes like sum([1, None]).
Activity
Akuli commentedon Apr 1, 2022
It's easy to put a TypeVar bound on the first overload, but
sum()doesn't work for strings even if you definestart="". It intentionally works with everything except strings.Fixing this properly would require python/typing#1043.
AlexWaygood commentedon Apr 1, 2022
Even that's actually a little tricky, because you get into the question of what is a number.
For example, this works fine, even though there's not really anything that these classes all have in common either from a nominal or structural point of view:
This does too:
But these all break:
JelleZijlstra commentedon Apr 1, 2022
We could at least bound the TypeVar to a Protocol defining
__add__. That wouldn't help with Alex's mixed numeric types, but it would help type checkers catch plausible mistakes likesum([1, None]).