[Python-ideas] A meaningful `if counter:`

Raymond Hettinger raymond.hettinger at gmail.com
Wed Apr 6 01:54:15 CEST 2011


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



More information about the Python-ideas mailing list