[Python-Dev] Real-world use of Counter
MRAB
python at mrabarnett.plus.com
Wed Nov 5 19:09:50 CET 2014
On 2014-11-05 16:33, Ethan Furman wrote:
> I'm looking for real-world uses of collections.Counter, specifically to see if anyone has been surprised by, or had to
> spend extra-time debugging, issues with the in-place operators.
>
> If sufficient and/or compelling use-cases are uncovered, the behavior of Counter may be slightly modified.
>
> Background:
>
> Most Python data types will cause a TypeError to be raised if unusable types are passed in:
>
> --> {'a': 0}.update(5)
> TypeError: 'int' object is not iterable
>
> --> [1, 2, 3].extend(3.14)
> TypeError: 'float' object is not iterable
>
> --> from collections import Counter
> --> Counter() + [1, 2, 3]
> TypeError: unsupported operand type(s) for +: 'Counter' and 'list'
>
> Most Counter in-place methods also behave this way:
>
> --> c /= [1, 2, 3]
> TypeError: unsupported operand type(s) for /=: 'Counter' and 'list'
>
> However, in the case of a handful of Counter in-place methods (+=, -=, &=, and |=), this is what happens instead:
>
> --> c += [1, 2, 3]
> AttributeError: 'list' object has no attribute 'items'
>
> Even worse (in my opinion) is the case of an empty Counter `and`ed with an incompatible type:
>
> --> c &= [1, 2, 3]
> -->
>
> No error is raised at all.
>
> In order to avoid unnecessary code churn (the fix itself is quite simple), the maintainer of the collections module
> wants to know if anybody has actually been affected by these inconsistencies, and if so, whether it was a minor
> inconvenience, or a compelling use-case.
>
> So, if this has bitten you, now is the time to speak up! :)
>
Whenever I've used the Counter class, I've known it was a counter, and
not tried to do any of the above, but at least, if I did, I'd get an
exception (or hope I do).
The final example, however, is odd. I think that one should be fixed.
More information about the Python-Dev
mailing list