microsoft / microsoft/pyright

Type arithmetic inconsistency

Open
#10,993 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
15.6k
Forks
1.8k
Avg merge
12h 13m
Merged PRs (30d)
52

Description

**Describe the bug**
This came up while annotating a list of flags. The in-place OR operator does not behave as expected when it comes to `Literal`s. This is perhaps understandable if extending the type level arithmetic to those comes with unforeseen consequences or unwarranted complexity, however what is more puzzling is the change in behaviour of `a[0] | two` when it is inside a `for` loop.

**Code**
```python
from typing import Literal

two: Literal[2] = 2

a: list[Literal[0, 1, 2, 3]] = []

reveal_type(a[0] | two) # Literal[2, 3]
a[0] = a[0] | two # OK
for _ in [...]:
reveal_type(a[0] | two) # int
a[0] = a[0] | two # ERROR

b: list[Literal[0, 1, 2, 3]] = []
b[0] |= two # ERROR
```

**VS Code extension or command-line**
Command-line, version `1.1.406`

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 command-line reproduction against Pyright version 1.1.406 and compare the reveal_type results and assignment errors inside and outside the loop. Trace the type-checking path for Literal arithmetic, indexed assignment, and in-place OR; done when the inconsistent behavior is explained and covered by a regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, 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.