python / python/mypy

List constant expression treated differently to list literal

Open
#21,710 2 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

When assigning a list literal to a variable with a known type, mypy uses that type in inferring the type of the list literal. This gives the appearance that invariance is relaxed e.g.

x: list[int | None] = [0, 1, 2, 10]  # ok

is accepted even though normally a list[int] cannot be assigned to a list[int | None].

However, when the list literal is written as a more complex expression, that stops working:

x: list[int | None] = [0, 1, 2] + [10]  # error

That's obviously a bit contrived. My actual use case is more similar to this:

x: list[int | None] = [i for i in range(3)] + [10]  # error

Maybe this isn't fixable - it's only sound because list.__add__ returns a new list which has no other references, but I don't think there is a way to represent that in typeshed.

To Reproduce

x: list[int | None] = [0, 1, 2] + [10]

Expected Behavior

No error

Actual Behavior

concat2.py:1: error: Incompatible types in assignment (expression has type "list[int]", variable has type "list[int | None]")  [assignment]
concat2.py:1: note: "list" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
concat2.py:1: note: Consider using "Sequence" instead, which is covariant

Your Environment

  • Mypy version used: 2.2.0
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.12.3

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

No implementation file or test is named in the issue. Start by reproducing the reported assignment with mypy, then trace how list literals, list concatenation, and comprehensions are inferred and checked against the annotated variable. Done means the reported concatenation cases pass without weakening ordinary list invariance checks.

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
Quiet
Clarity
Mostly clear
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.