python / python/mypy

`--strict-equality` flag not working with membership operator and `Literal` types

Open
#17,062 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-literal-types topic-overlap
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

When using any container (set, frozenset, list, tuples...) containing Literal based types, the --strict-equality is not detecting any issues when I use the membership operator in a non-overlapping check.

To Reproduce

from typing import Literal

OPTIONS = Literal["a", "b"]
var: list[OPTIONS] = ["a"]
if "c" in var:  # MYPY OK
    pass

Expected Behavior

When the flag --strict-equality is set, I would expect that mypy raises an erorr here. Same as it does when I do a non-overlapping equality check:

from typing import Literal

OPTIONS = Literal["a", "b"]
var: list[OPTIONS] = ["a"]
if var[0] == "c":  #  error: Non-overlapping equality check (left operand type: "Literal['a', 'b']", right operand type: "Literal['c']")  [comparison-overlap]
    pass

Actual Behavior

No errors are raised

Your Environment
Using Mypy version 1.9.0

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 the reported Python reproduction with --strict-equality and compare its membership check with the indexed equality check. Locate the strict-equality and membership-analysis entry points, then add a regression test covering a container of Literal values. Done means mypy reports a non-overlapping check for the membership expression without regressing valid membership checks.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.