Message230410
Nevertheless, that is the behavior if NotImplemented is returned by a method. Here's some code to demonstrate:
--8<---------------------------------------
from collections import Counter
class Spam(int):
"for sake of example"
def __radd__(self, other):
other[self] = other[self] + 1
return other
s = Spam(5)
c = Counter()
print(c)
c += s
print(c)
c += 9
--8<---------------------------------------
before the patch
-------------------------------------------
Counter()
Traceback (most recent call last):
File "blah.py", line 13, in <module>
c += s
File "/home/ethan/source/python/issue20284/Lib/collections/__init__.py", line 738, in __iadd__
for elem, count in other.items():
AttributeError: 'Spam' object has no attribute 'items'
-------------------------------------------
after the patch
-------------------------------------------
Counter()
Counter({5: 1})
Traceback (most recent call last):
File "blah.py", line 13, in <module>
c += 9
TypeError: unsupported operand type(s) for +=: 'Counter' and 'int'
-------------------------------------------
As you can see, we get better support for other objects that know how to add themselves to the container in question, and a nicer and more correct error message for objects that do not.
As I said earlier, the only decision we should have to make here is whether to check for a Counter, or just something with a .items attribute, but either way we should be returning NotImplemented. |
|
Date |
User |
Action |
Args |
2014-10-31 23:01:19 | ethan.furman | set | recipients:
+ ethan.furman, rhettinger, pitrou, r.david.murray, Joshua.Chin |
2014-10-31 23:01:19 | ethan.furman | set | messageid: <1414796479.41.0.0207054088675.issue22766@psf.upfronthosting.co.za> |
2014-10-31 23:01:19 | ethan.furman | link | issue22766 messages |
2014-10-31 23:01:19 | ethan.furman | create | |
|