[New-bugs-announce] [issue43062] Non-integer values in collections.Counter

HuangFuSL report at bugs.python.org
Fri Jan 29 09:50:25 EST 2021

New submission from HuangFuSL <huangfusl at outlook.com>:

When I am creating a counter object provided by `collections.Counter` using a mapping object like a dictionary, it seems that Python will not check the validity of the values in the mapping object.

I've checked the following Python script could be successfully executed using Python 3.9.0 on Windows.

>>> from collections import Counter
>>> a = Counter({'0': '0'})
>>> a.elements()
<itertools.chain object at 0x00000252DDB5A4F0>

`a.elements()` returns a iterator, iterating through it will normally get the records counted by the `Counter`, but with a `str` object inside, iterating through it will make a `TypeError` raised.

>>> for i in a.elements():
...     pass
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer

Meanwhile, if the counter contains values that cannot be compared such as `False` and `''`, `most_common()` method will fail.

>>> b = Counter({'0': False, '1': ''})
>>> b.most_common()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python39\lib\collections\__init__.py", line 610, in most_common
    return sorted(self.items(), key=_itemgetter(1), reverse=True)
TypeError: '<' not supported between instances of 'bool' and 'str'

The `sys.version` variable of my Python interpreter is as follows:

>>> import sys
>>> sys.version
'3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)]'

I'm not sure whether the result is intentionally designed, but I think such execution results may lead to confusion.

components: Extension Modules
messages: 385913
nosy: HuangFuSL
priority: normal
severity: normal
status: open
title: Non-integer values in collections.Counter
type: behavior
versions: Python 3.9

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list