[Python-ideas] A meaningful `if counter:`
cool-RR
cool-rr at cool-rr.com
Wed Apr 6 08:59:41 CEST 2011
On Wed, Apr 6, 2011 at 1:54 AM, Raymond Hettinger <
raymond.hettinger at gmail.com> wrote:
>
> On Apr 5, 2011, at 2:16 PM, cool-RR wrote:
>
> > Hello folks,
> >
> > I noticed today that bool(Counter({'a': 0'})) is True.
> >
> > Is this wise? I want to be able to do:
> >
> > if my_counter:
> > whatever
>
> As explained on tracker where you made the same request,
> that counter is not an empty container. Accordingly, it's bool
> value is True. The python language has been consistent
> with this for a long time (as I found-out years ago when
> I proposed putting a __len__ attribute on various iterools
> when the output iterator length was known, but Guido
> wanted the iterator to always have a bool value of False).
>
> A Counter object is essentially just a dictionary with a
> __missing__ method to supply an implied zero default count.
> Accordingly, it needs to behave as much like a dictionary
> as possible.
>
>
> Raymond
>
Okay, this argument applies against `Counter.__bool__`, but not against
`Counter.elements().__bool__`. So I want to hear whether people would find a
`Counter.elements().__bool__` method useful.
Ram.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110406/e1e38144/attachment.html>
More information about the Python-ideas
mailing list