Specifying the return type of `__abs__` to be a `TypeVar` causes `expected "SupportsAbs[<nothing>]` error
Open
Nobody has claimed this yet.
bug
false-positive
priority-1-normal
topic-type-variables
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Specifying the return type of __abs__ to be a TypeVar causes expected "SupportsAbs[<nothing>] error
The following works fine:
from typing import TypeVar
T = TypeVar("T", bound="Number")
class Number:
def __abs__(self: T):
return self
def square(self: T) -> T:
return self
def myabs(x: T) -> T:
return abs(x)
x = myabs(Number())
x.square()
But this produces an error:
from typing import TypeVar
T = TypeVar("T", bound="Number")
class Number:
def __abs__(self: T) -> T:
return self
def square(self: T) -> T:
return self
def myabs(x: T) -> T:
return abs(x)
x = myabs(Number())
x.square()
- What is the actual behavior/output?
error: Argument 1 to "abs" has incompatible type "T"; expected "SupportsAbs[<nothing>]"
- What is the behavior/output you expect?
No error, like in the first example.
- What are the versions of mypy and Python you are using?
Python 3.6 and MyPy 0.761
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing both Python snippets with mypy 0.761 and compare how the two abs return annotations affect the abs(x) call. Trace the type-checking path for SupportsAbs and TypeVar bounds; done when the annotated version produces no incompatible-argument error like the unannotated version.
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
- 42/100