python / python/mypy

Containment checks for separate types raises error

Open
#16,089 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

Bug Report

If a containment check is done on non-overlapping types, mypy reports an error although the code is type safe.

Further information: https://github.com/python/typing/discussions/1464

To Reproduce

from enum import Enum

class Foo(str, Enum):
   BAR = "bar"

contains = "foo" in iter(Foo)
# or, even more simple but unusual code:
contains = "foo" in iter([1])

Expected Behavior

The code is type safe. The first example actually checks the containment in the iterator, the second example will always return false, but is still valid code. Mypy should not report an error for either case.

Actual Behavior

test.py:6: error: Unsupported operand types for in ("str" and "Iterator[Foo]")  [operator]
test.py:8: error: Unsupported operand types for in ("str" and "Iterator[int]")  [operator]

Your Environment

  • Mypy version used: 1.5.1
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 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 by running mypy on the reproducer in the issue and trace the containment/operator type-checking path. Add a regression test for both iterator examples, then verify that mypy accepts them without weakening valid incompatible-type diagnostics.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 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.