This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: docs: operator dunder (`__add__`, et al.) invocations described incorrectly
Type: enhancement Stage: resolved
Components: Documentation Versions: Python 3.10, Python 3.9, Python 3.8, Python 3.7, Python 3.6
process
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: docs@python Nosy List: brett.cannon, docs@python, wchargin
Priority: normal Keywords: patch

Created on 2020-09-03 20:30 by wchargin, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Pull Requests
URL Status Linked Edit
PR 22084 merged wchargin, 2020-09-03 20:40
Messages (2)
msg376316 - (view) Author: William Chargin (wchargin) * Date: 2020-09-03 20:30
The operator override dunder methods, like `__add__`, are described in
the “Data model” docs here:
<https://docs.python.org/3.10/reference/datamodel.html#object.__add__>

Those docs say:

> For instance, to evaluate the expression `x + y`, where `x` is an
> instance of a class that has an `__add__()` method, `x.__add__(y)` is
> called.

But this is not correct: `x + y` always uses `type(x).__add__`, which
may be different from `x.__add__` if `__add__` has been set directly on
the instance.

Demonstration:

```
class C:
    def __add__(self, other):
        return "from class"


c = C()
print(c + c)  # prints "from class"

c.__add__ = lambda other: "from instance"
print(c.__add__(c))  # prints "from instance"
print(type(c).__add__(c, c))  # prints "from class"

print(c + c)  # prints "from class"!
```

The same issue appears in the reversed operator dunder (`__radd__`,
et al.) docs below.

I have a patch that I can submit as a PR; just need a bpo number.
msg398954 - (view) Author: Brett Cannon (brett.cannon) * (Python committer) Date: 2021-08-04 20:43
New changeset 80f33f266b4ad5925a3e58ea3a54ae139a6b6f0e by William Chargin in branch 'main':
bpo-41706: Fix special method invocation docs to mention using type() (GH-22084)
https://github.com/python/cpython/commit/80f33f266b4ad5925a3e58ea3a54ae139a6b6f0e
History
Date User Action Args
2022-04-11 14:59:35adminsetgithub: 85872
2021-08-05 00:08:48brett.cannonsetstatus: open -> closed
resolution: fixed
stage: patch review -> resolved
2021-08-04 20:43:15brett.cannonsetnosy: + brett.cannon
messages: + msg398954
2020-09-03 20:40:56wcharginsetkeywords: + patch
stage: patch review
pull_requests: + pull_request21170
2020-09-03 20:30:50wchargincreate