python / python/mypy

__iadd__ is not applied for += when TypeVars with bound are used.

Open
#11,745 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-protocols topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

Using += with TypeVar bound on Protocol implementing __iadd__ causes error:

Unsupported left operand type for + ("U")

To Reproduce

Define Protocol and generic method as shown below.

# main.py


from __future__ import annotations
from typing import Generic, Protocol, TypeVar     


T = TypeVar("T")
U = TypeVar("U", bound=SupportsIAdd)


class SupportsIAdd(Protocol):
    def __iadd__(self: T, other: T) -> T: ...        


class AddingAccumulatorParam(Generic[U]):
    def addInPlace(self, value1: U, value2: U) -> U:
        value1 += value2  # Fails
        return value1

Expected Behavior

It should pass mypy checks, as U is bound on SupportIAdd which in turn provides __iadd__ that can be used for +=.

Actual Behavior

The snippet shown above fails with:

main.py:17: error: Unsupported left operand type for + ("U")
Found 1 error in 1 file (checked 1 source file)

Replacing __iadd__ with __add__ makes mypy happy (so clearly mypy can infer required operation and fall back with +).

# main.py

from __future__ import annotations
from typing import Generic, Protocol, TypeVar     


T = TypeVar("T")
U = TypeVar("U", bound=SupportsIAdd)


class SupportsIAdd(Protocol):
    def __add__(self: T, other: T) -> T: ... 


class AddingAccumulatorParam(Generic[U]):
    def addInPlace(self, value1: U, value2: U) -> U:
        value1 += value2  # Passes just fine
        return value1

On Further investigation, it seems like the issue might be related to bound TypeVar ‒ if I replace Protocol

class SupportsIAdd(Protocol):

with plain class

class SupportsIAdd:

the problem still exists, but if I tweak the signature of the method that uses it, to take exact class

# main.py

from __future__ import annotations
from typing import Any, TypeVar              


class SupportsIAdd:          
    def __iadd__(self, other: Any) -> SupportsIAdd: ...         


class AddingAccumulatorParam:            
    def addInPlace(self, value1: SupportsIAdd, value2: SupportsIAdd) -> SupportsIAdd:            
        value1 += value2
        return value1

it passes.

Finally (credit goes to @hauntsaninja) applying __iadd__ directly

class AddingAccumulatorParam(Generic[U]):
    def addInPlace(self, value1: U, value2: U) -> U:
        return reveal_type(value1.__iadd__(value2))

yields expected result

main.py:17: note: Revealed type is "U`1"

Your Environment

  • Mypy version used: Both 0.910 and dev.
  • Mypy command-line flags: Default flags.
  • Mypy configuration options from mypy.ini (and other config files): No additional config used.

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 reproducing the examples in main.py with mypy using the default flags, comparing += with direct iadd and add calls. Add regression coverage for a bound TypeVar with a Protocol iadd; done when the example passes without the unsupported-left-operand error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.