python / python/mypy

`functools.reduce` over sets becomes unacceptable when used in a larger expression

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

Nobody has claimed this yet.

bug topic-type-context
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:
    emptyset: frozenset[str] = frozenset()

    # OK
    reduce(frozenset.union, loop_nests[:-1], emptyset)

    # Error
    inames_to_pull_out - reduce(frozenset.union, loop_nests[:-1], emptyset)

Here is what mypy says as of 1.11.1:

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

This seems spurious: It's not clear to me why this should be acceptable as a stand-alone expression, but not within a larger expression. Pyright (1.1.376) also seems to like this code just fine.

See also #17693.

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

Reproduce the diagnostic from the code shown in mypybug.py, comparing the standalone reduce call with the same call used in the set subtraction expression. Trace how mypy infers and checks functools.reduce in that context; done means the valid expression is accepted without weakening errors for genuinely incompatible reduce calls.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.