python / python/mypy

Incorrectly narrowed Literal in while loops

Open
#17,096 4 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

The following code snippet:

from typing import Literal


class Node:
    color: Literal["red", "black"]
    next: Node


def walk(node: Node) -> None:
    while node.color == "red":
        node = node.next
    reveal_type(node.color)
    while True:
        reveal_type(node.color)
        if node.color == "red":
            return
        node = node.next
        reveal_type(node.color)

Results in a comparison-overlap false positive under mypy --strict:

test.py:12: note: Revealed type is "Literal['black']"
test.py:14: note: Revealed type is "Literal['black']"
test.py:15: error: Non-overlapping equality check (left operand type: "Literal['black']", right operand type: "Literal['red']")  [comparison-overlap]
test.py:18: note: Revealed type is "Union[Literal['red'], Literal['black']]"
Found 1 error in 1 file (checked 1 source file)

As you can see, mypy correctly concludes that at line 12, node.color must be "black", and at line 18, it may be "red" or "black". But at line 14, it still thinks that it must be "black" even though it may not be on subsequent iterations. This causes the false positive on line 15.

To Reproduce

https://mypy-play.net/?mypy=master&python=3.12&flags=strict&gist=3207b91810da9f447ff090d86df689a5

Your Environment

  • Mypy version used: tested on 1.10.0+dev.80190101f68b52e960c22572ed6cc814de078b9c and 1.8.0
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.12.2

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 snippet with mypy --strict and compare narrowing at the three reveal_type sites. Trace the while-loop control-flow and type-narrowing logic; done when the second loop does not retain the first loop's narrowing, the comparison-overlap error disappears, and the revealed types match the report.

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.