variance okay for literals, but not expressions ([1, 2] okay for list[int | None] but [1] + [2] is error)
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
a: list[int | None] = [1] + [2] + [None]
b: list[int | None] = [1] + [2]
c: list[int | None] = [1, 2]
a is okay, b is an error, c is okay
Apologies if this is a repeat / common issue. I couldn't find anything in the docs. This is popping up for me a lot, my interpretation is that mypy allows type invariance on literals that it will not for expressions.
To Reproduce
https://mypy-play.net/?mypy=latest&python=3.11&gist=b999a1bd2e975645b868c0b376c910e8
Expected Behavior
Either b and c should both be errors or (preferably) neither.
Actual Behavior
b is an error but c isn't
Your Environment
- Mypy version used: 1.7.1 and master
- Python version used: 3.11
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the linked mypy-play reproduction with mypy 1.7.1 or master and Python 3.11, comparing the diagnostics for assignments a, b, and c. Done means the behavior for [1] + [2] agrees with the behavior for [1, 2], according to the expected behavior stated in the issue.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100