[Python-ideas] Fwd: collections.Counter should implement fromkeys

Tim Peters tim.peters at gmail.com
Fri Jun 29 18:56:02 EDT 2018

Reposting because the original got bounced from Google Groups.

---------- Forwarded message ---------
From: Tim Peters <tim.peters at gmail.com>
Date: Fri, Jun 29, 2018 at 5:54 PM
Subject: Re: [Python-ideas] collections.Counter should implement fromkeys
To: <abedillon at gmail.com>
Cc: python-ideas <python-ideas at googlegroups.com>

[Abe Dillon <abedillon at gmail.com>]
> ...
> I'm using the copy-constructor because I know Counter is a subclass of
> I'm using fromkeys because I know how that class method works.
> So why does the subclass lack functionality that the superclass has?
> Because programmers wouldn't be able to wrap their heads around it?
> I don't buy it. This feels like nanny-design trumping SOLID design

More because Counter.fromkeys() could be incoherent.  From the
implementation (in your Lib/collections/__init__.py):

    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)

For a dict, a value appearing multiple times in the iterable doesn't
matter.  But a fundamental use case for Counters is to tally the _number_
of times duplicate keys appear.  So, e.g., someone will be unpleasantly
surprised no matter what:

Counter.fromkeys("aaaaa", 2)

returned.  "It should set key 'a' to 2!  that's what I said it should do!"
"No!  It should set key 'a' to 10!  that's what a Counter _always_ does -
sums the values associated with duplicate keys!" "You're both right - and
wrong!  It should raise an exception if there's a duplicate key, because
there's no compelling answer to what it should do!"

I expect Raymond called it NotImplementedError instead so he could release
the code instead of waiting 3 years for that debate to end ;-)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180629/2da202cd/attachment.html>

More information about the Python-ideas mailing list