Counter Class -- Bag/Multiset

msrachel.e at msrachel.e at
Fri Jan 23 09:53:04 CET 2009

On Jan 23, 12:27 am, bearophileH... at wrote:
> bearophile:
> > Are keys restricted to be long and int values only? Or are they
> > general (referenced) objects + a control of their integral nature?
> Here I meant values, sorry.
> Also: what's the rationale of allowing negative values too?

The dict values can be anything, but only ints make sense in the
context of bags/multisets/counters etc.
Since it is a dict subclass, we really have no control of the
content.  It's pretty much a "consenting adults" data structure (much
like the heapq module which cannot enforce a heap condition on the
underlying list which is exposed to the user).

To block negative values, the setter methods would have to be
overridden and would dramatically slow down the major use cases for
counters (and we would not be able to let people freely convert to and
from arbitrary dicts).  Also, we would have to introduce and document
some kind of exception for attempts to set a negative value (i.e. c[x]
-= 1 could raise an exception).  This would unnecessarily complicate
the API in an attempt to limit what a user can do (perhaps barring
them from a use case they consider to be important).

So, if you don't want negative counts, I recommend that you don't
subtract more than you started off with ;-)


More information about the Python-list mailing list