python / python/mypy

Wrong inference for `abs/__abs__` or function that calls a method on a generic type.

Open
#19,609 0 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

This was discussed in the typing forums.

Here mypy (latest version 1.17.1) infers the type of abs(value) incorrectly:

from typing import Self

class Real:
    def __abs__(self) -> Self:
        return self

def my_abs[T: Real](value: T):
    reveal_type(abs(value))      # Real
    reveal_type(value.__abs__()) # T

That is:

$ mypy z.py 
z.py:8: note: Revealed type is "z.Real"
z.py:9: note: Revealed type is "T`-1"
Success: no issues found in 1 source file

Since abs just calls __abs__ they return the same type which should be inferred as T in both cases.

I show the simpler example above with a concrete Real type but what I actually want to do is have a Protocol for abs:

from typing import Self, Protocol

class HasAbs(Protocol):
    def __abs__(self) -> Self:
        return self

def my_abs[T: HasAbs](value: T) -> T:
    return abs(value)

However mypy incorrectly rejects this because it infers the type of abs(value) incorrectly:

$ mypy z.py 
z.py:8: error: Incompatible return value type (got "HasAbs", expected "T")  [return-value]
Found 1 error in 1 file (checked 1 source file)

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 with the z.py examples in the issue and run mypy 1.17.1 to reproduce the differing revealed types and rejected return value. Trace how abs(value) is inferred versus value.abs(), then add a regression test showing that a generic value constrained by HasAbs retains type T and passes type checking.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.