datetimes `__sub__` is not symmetrical in subclass.
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
import datetime
from typing import Any
class MyDatetime(datetime.datetime):
def __eq__(self, other: Any) -> bool:
if isinstance(other, datetime.datetime):
delta = self - other # error: No overload variant of "__sub__" of "datetime" matches argument type "datetime" [operator]
delta = other - self # OK
return True
else:
return NotImplemented
python: 3.9
mypy: 0.950
playground: https://mypy-play.net/?mypy=0.950&python=3.9&gist=ac2ffa60be085e552cb67043afa59e07
The applicability of the superclass __sub__ method is only recognized for datetime - MyDatetime, but not for MyDatetime - datetime.
Looking into typeshed, there is this annotation:
_D = TypeVar("_D", bound=date)
class datetime(date):
if sys.version_info >= (3, 8):
def __sub__(self: _D, __other: _D) -> timedelta: ...
else:
def __sub__(self, __other: datetime) -> timedelta: ...
Telling mypy that the python version is 3.7 gets rid of the error, so there seems to be some issue, where the _Ds are not treated the same way depending on the order of operations.
The same error is not reported for mypy 0.921 and earlier: https://mypy-play.net/?mypy=0.921&python=3.9&gist=ac2ffa60be085e552cb67043afa59e07
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 running the linked mypy-play reproducer with Python 3.9 and comparing behavior between mypy 0.921 and 0.950. Then inspect the typeshed datetime.sub annotations, focusing on the _D type variable and operand order; done means both subtraction directions type-check consistently for the subclass example.
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
- 38/100