[Python-ideas] Support floating-point values in collections.Counter

Steven D'Aprano steve at pearwood.info
Tue Dec 19 06:04:35 EST 2017

On Mon, Dec 18, 2017 at 11:51:46PM +0000, Joel Croteau wrote:

> It would be useful in many scenarios for values in collections.Counter to
> be allowed to be floating point.

Can you give a concrete example?

> I know that Counter nominally emulates a multiset,
> which would suggest only integer values, but in a more general
> sense, it could be an accumulator of either floating point or integer data.
> As near as I can tell, Collection already does support float values in both
> Python 2.7 and 3.6, and the way the code is implemented, this change should
> be a no-op. All that is required is to update the documentation to say
> floating-point values are allowed, as it currently says only integers are
> allowed.

I don't think its that simple.

What should the elements() method do when an element has a "count" of 
2.5, say? What happens if the count is a NAN? There are operations that 
discard negative and zero, or positive and zero, counts. How should they 
treat -0.0 and NANs? 

I am intrigued by this suggestion, but I'm not quite sure where I would 
use such an accumulator, or whether a Counter is the right solution for 
it. Perhaps some concrete use-cases would convince me.


More information about the Python-ideas mailing list