Search code examples
pythoninheritanceabstractpython-collections

Inherit from collections.Counter: 'fromkeys' is abstract


I have a python class that inherit from collections.Counter:

class Analyzer(collections.Counter):
   pass

When I use pylint on this code, its answer is:

W: Method 'fromkeys' is abstract in class 'Counter' but is not overridden (abstract-method)

I checked the implementation of collections.Counter on my machine, and effectively, this method is not implemented (and a comment helps to understand why):

class Counter(dict):
    ...
    @classmethod
    def fromkeys(cls, iterable, v=None):
        # There is no equivalent method for counters because setting v=1
        # means that no element can have a count greater than one.
        raise NotImplementedError(
            'Counter.fromkeys() is undefined.  Use Counter(iterable) instead.')

However, I don't really know how to implement this method, if Counter itself does not…

What is the way to solve this warning in this situation?


Solution

  • There is two separate way of thinking.

    • Consider Counter as abstract (as pylint does, as Jared explained). Then, the class Analyzer must implement fromkeys or also be abstract. But then, one should not be able to instanciate Counter.
    • Consider Counter as concrete, even if you cannot use its fromkeys method. Then, pylint's warning must be disabled (as it is wrong in this case, see Jared's answer to kown how), and the class Analyzer is also concrete and does not need to implement this method.