Solving "error: Unsupported left operand type for + ("Iterable[str]") [operator]"

Viewed 389

I have code that accepts a list of strings, and turns them into a list of tokens (i.e. all strings are combined and flattened)

For example, ['a b', 'c', 'd e'] => ['a', 'b', 'c', 'd', 'e']

Like so:

l = ['a b', 'c', 'd e']
set(reduce(lambda a, b: a + b.split(), l, []))

Unfortunately, mypy is not happy, and it gives the message: error: Unsupported left operand type for + ("Iterable[str]") [operator].

As shown by this answer, it's because sequences do not necessarily implement __add__.

So, is there a way to use the code set(reduce(lambda a, b: a + b.split(), l, [])) and have it be compatible with mypy?

1 Answers

With cast you can use lambda (else use a def function):

l = ['a b', 'c', 'd e']
reduce(lambda a, b: cast(list, a) + b.split(), l, [])
Related