mypy icon indicating copy to clipboard operation
mypy copied to clipboard

`functools.reduce` over sets: empty set not accepted without annotation

Open inducer opened this issue 1 year ago • 0 comments

Reproducer:

from typing import Collection
from functools import reduce


def _pull_out_loop_nest(
            loop_nests: list[frozenset[str]],
            inames_to_pull_out: frozenset[str]
        ) -> None:
    # OK
    emptyset: frozenset[str] = frozenset()
    assert inames_to_pull_out <= reduce(frozenset.union, loop_nests, emptyset)

    # Error
    assert inames_to_pull_out <= reduce(frozenset.union, loop_nests, frozenset())

Here is what mypy says as of 1.11.1:

mypybug.py:14: error: Argument 1 to "reduce" has incompatible type "Callable[[frozenset[_T_co], VarArg(Iterable[_S])], frozenset[_T_co | _S]]"; expected "Callable[[frozenset[Never], frozenset[str]], frozenset[Never]]"  [arg-type]

This seems spurious: It seems that something picks up the type of the empty set somewhat too eagerly. Pyright (1.1.376) also seems to like this code just fine.

inducer avatar Aug 20 '24 19:08 inducer