[issue45313] Counter.elements() wrong error message

Raymond Hettinger report at bugs.python.org
Tue Sep 28 20:43:03 EDT 2021


Raymond Hettinger <raymond.hettinger at gmail.com> added the comment:

The elements() method is working correctly:

    >>> from collections import Counter
    >>> aCounter = Counter('abracadabra')
    >>> list(aCounter.elements())
    ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'r', 'r', 'c', 'd']

No arguments should be passed into elements, so this code is incorrect:

    aCounter.elements(1)

You may have expected that the error message would say:

    TypeError: Counter.elements() takes 0 positional argument but 1 was given

Instead, you observed the counts were one higher than you expected.

This is due to how Python implements object oriented programming.

The call:

    aCounter.elements(1)

is effectively translated to:

    Counter.elements(aCounter, 1)

which does in fact have two arguments.

No one really likes the error message, but it has been deemed hard to fix and we just live with it.

Note, this isn't specific to Counter.  All pure python classes work this way:

    >>> class A:
            def m(self, x):
                pass
        
    >>> a = A()
    >>> a.m(10, 20)
    Traceback (most recent call last):
      File "<pyshell#10>", line 1, in <module>
        a.m(10, 20)
    TypeError: m() takes 2 positional arguments but 3 were given

----------
nosy: +rhettinger
resolution:  -> wont fix
stage:  -> resolved
status: open -> closed

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45313>
_______________________________________


More information about the Python-bugs-list mailing list