'mypy: Unsupported left operand type error when adding two strings together

I have a function that looks like this:

from typing import Sequence

def test(a: Sequence[str]):
    b: Sequence[str] = ["test1"]
    c: Sequence[str] = a+b

test(["test2"])

mypy returns the error Unsupported left operand type for + ("Sequence[str]") in the line where c is defined. How can I rewrite this function to make it work?



Solution 1:[1]

The doc for typing.Sequence :

A generic version of collections.abc.Sequence.

The doc for collections.abc.Sequence speaks not of __add__ (the protocol method for addition).
The recap table neither.

It needs to be implemented, like suggested in this answer to python Generic Type Hints + user-defined container + constraining to Types implementing add method. Here is the MyPy doc on protocols.

I tried something along that way, but it sill not typechecks :

from typing import Sequence, Protocol, TypeVar


T = TypeVar('T')
class SelfAddable(Protocol[T]):
    def __add__(self: T, other: T) -> T:
        ...


X = TypeVar('X')
class AddableSequence(Sequence[X], SelfAddable):
    pass


def foo(a: AddableSequence[str]):
    b: AddableSequence[str] = ["test1"]
    c: AddableSequence[str] = a+b


foo(["test2"])

# reveal_type(list.__add__)
# Revealed type is "def [_T] (builtins.list[_T`1], builtins.list[_T`1]) -> builtins.list[_T`1]"
so70940005.py:16: error: Incompatible types in assignment (expression has type "List[str]", variable has type "AddableSequence[str]")
so70940005.py:20: error: Argument 1 to "foo" has incompatible type "List[str]"; expected "AddableSequence[str]"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lenormju