python / python/mypy

Spurious error when adding two list

Open
#15,087 3 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

Mypy reports Unsupported operand types for + when concatenating two lists, when the second operand is a subtype of the first.

This was previously mentioned in this comment in #5492

Below is a simple concise example

To Reproduce

class A:
    pass


class B(A):
    pass


def foo(a: list[A]) -> None:
    pass


l1: list[A] = [A(), B()]
l2: list[B] = [B()]
l3 = l1 + l2
foo(l2 + l1)  # OK, no error
foo(l3)  # also OK
foo(
    l1 + l2
)  # ERROR: Unsupported operand types for + ("List[A]" and "List[B]")  [operator]mypy(error)

gist link

Expected Behavior
No error on the last line

Actual Behavior
Reports spurious error

Your Environment

  • Mypy version used: mypy 1.2.0
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): from pyproject.toml
ignore_missing_imports = true
show_column_numbers = true
warn_redundant_casts = true
warn_unused_ignores = true
warn_unused_configs = true
follow_imports = "normal"

plugins = ["pydantic.mypy"]
  • Python version used: 3.10

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 concise Python example with mypy 1.2.0 and compare the diagnostics for l1 + l2 and l2 + l1. The issue names no source file or test path, so trace the list-addition type-checking path from this reproduction. Done means the final l1 + l2 expression produces no unsupported-operand error while the existing valid cases remain valid.

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
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.