python / python/mypy

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

Open
#17,693 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the reproducer in mypybug.py and run it against mypy 1.11.1, comparing the annotated and unannotated empty frozenset cases. Trace the reduce type inference involved and add a regression test showing that the unannotated form no longer produces the reported diagnostic.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.