python / python/mypy

`x in y` doesn't report errors when `x` is not `str` and `y: union | involving | str`

Open
#21,595 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-union-types
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

This doesn't report an error but can easily crash at runtime:

var: list[int] | str
2 in var

Expected Behavior

var: list[int] | str
2 in var  # E: Unsupported operand types for in ("int" and "str") \
          # N: Right operand is of type "list[int] | str"

Your Environment

  • Mypy version used: 1.0.0-2.1.0
  • Mypy command-line flags: --strict

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 reproducing the example with mypy under --strict: var: list[int] | str followed by 2 in var. Trace the type-checking path for the in operator and make it report the expected unsupported operand error for the str union member without missing the possible runtime failure.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.