Counter Class -- Bag/Multiset

msrachel.e at gmail.com msrachel.e at gmail.com
Fri Jan 23 03:53:04 EST 2009


On Jan 23, 12:27 am, bearophileH... at lycos.com 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 ;-)

Raymond



More information about the Python-list mailing list