2

From mypy's point of view l1 + l2 is OK. But returning l1 + l2 isn't OK. Why?

I'm using Python 3.11 and mypy 1.16.

def test() -> list[str | int]:
    l1: list[str | int]
    l2: list[int]
    l1 + l2  # OK
    return l1 + l2  # error: Unsupported operand types for + ("list[str | int]" and "list[int]")  [operator]
2
  • 3
    You can't do foo: list[str | int] = l1 + l2 either; it's not that you can't return it, so much that the result isn't assignable to list[str | int]. Possibly related to e.g. github.com/python/mypy/issues/3351. Commented Aug 1 at 16:00
  • the error might be because of the type checker’s strictness ont the value that you are returning Commented Aug 1 at 16:05

1 Answer 1

4

This is an old bug. It has been reported multiple times over the years, but never fixed. There is a draft PR that aims to resolve it.


A potentially interesting observation is that extracting l1 + l2 to an unannotated variable l causes the error to disappear, but not if l is annotated with list[str | int]:

(playground)

l1: list[str | int] = []
l2: list[int] = []
l = l1 + l2
reveal_type(l)                # list[int | str]

return l                      # fine
l: list[str | int] = l1 + l2  # error
reveal_type(l)                # list[str | int]

return l                      # fine

As discussed in the aforementioned issue, the workaround is to use unpacking:

return l1 + l2     # error
return [*l1, *l2]  # fine
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.