Message230410
| Author |
ethan.furman |
| Recipients |
Joshua.Chin, ethan.furman, pitrou, r.david.murray, rhettinger |
| Date |
2014年10月31日.23:01:19 |
| SpamBayes Score |
-1.0 |
| Marked as misclassified |
Yes |
| Message-id |
<1414796479.41.0.0207054088675.issue22766@psf.upfronthosting.co.za> |
| In-reply-to |
| Content |
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. |
|