python / python/mypy

set.__and__ false-positive involving generic inference

Open
#15,462 1 comment 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

Bug Report

The way mypy does type inference breaks calling a generic function on the right side of set.__and__, because it takes an argument of type AbstractSet[object]. It seems like it is propagating 'object' instead of the more specific type and then complaining when that does not work.

I reported this as a comment on #5738, but this is apparently a different issue because this problem was not fixed when that issue was closed.

To Reproduce

from typing import TypeVar

T = TypeVar('T')

def identity(x: set[T]) -> set[T]:
    return x

x = {0, 1}

print({0} & identity(x))

Actual Behavior

$ mypy repr.py
repr.py:10: error: Argument 1 to "identity" has incompatible type "set[int]"; expected "set[object]"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

$ mypy --new-type-inference repr.py
repr.py:10: error: Argument 1 to "identity" has incompatible type "set[int]"; expected "set[object]"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 1.5.0+dev.0873230ee60461110bd7bfde7ca3886878aae389 (compiled: no)
  • Python version used: Python 3.11.3

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 supplied reproduction using mypy 1.5.0+dev and compare normal inference with --new-type-inference. Trace how the set.and operand is typed before identity(x) is checked. Done means the example type-checks without the incompatible set[int] versus set[object] error, while preserving relevant generic inference behavior.

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
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.