Skip to content

Adding lists of subtypes together #2383

Closed
@alanhdu

Description

@alanhdu

Using mypy==0.620 and Python 3.6.6, the following code:

from typing import List, Optional

x: List[Optional[int]] = [1, 2, 3]
[None] + x

fails with:

a.py:4: error: Unsupported operand types for + ("List[None]" and "List[Optional[int]]")

This is presumably because lists are invariant w.r.t their generic parameter, and the declration requires a List of the same type

def __add__(self, x: List[_T]) -> List[_T]: ...
.

I don't know what the right solution here is -- can we just replace the x: List[_T] with x: List[_T_co] and make it covariant? Or doe we need another typevar _U = TypeVar("U", bound=_T) or something?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions