typeshed icon indicating copy to clipboard operation
typeshed copied to clipboard

math.prod typing incorrect

Open karolinepauls opened this issue 1 year ago • 3 comments
trafficstars

Test file (decimal_prod.py):

from decimal import Decimal
from math import prod
from typing import TYPE_CHECKING

result = prod([Decimal(1), Decimal(2)])

if TYPE_CHECKING:
    reveal_type(result)
else:
    print(type(result))

Test:

$ mypy --version
mypy 1.10.0 (compiled: yes)
$ mypy decimal_prod.py
decimal_prod.py:8: note: Revealed type is "builtins.float"
Success: no issues found in 1 source file
$ python decimal_prod.py
<class 'decimal.Decimal'>

defined here: https://github.com/python/typeshed/blob/main/stdlib/math.pyi#L102-L105

karolinepauls avatar May 13 '24 15:05 karolinepauls

It sounds as if we should use a TypeVar here, but the existing overload makes me a bit anxious. Any fix should include tests to check a few use cases. (But as always: PR welcome!)

srittau avatar May 13 '24 15:05 srittau

Presumably all non-int return types should be a union with Literal[1]. No matter what type the sequence elements are, it is possible to get the integer 1 with an empty sequence:

>>> import math
>>> math.prod([])
1

Akuli avatar May 13 '24 18:05 Akuli

Presumably all non-int return types should be a union with Literal[1]. No matter what type the sequence elements are, it is possible to get the integer 1 with an empty sequence:

>>> import math
>>> math.prod([])
1

And now try:

>>> math.prod([], start=17)
> 17

real-or-random avatar May 16 '24 11:05 real-or-random