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

Raymond Hettinger raymond.hettinger at gmail.com
Fri Jun 29 23:45:48 EDT 2018

On Jun 29, 2018, at 5:32 PM, Abe Dillon <abedillon at gmail.com> wrote:
> Sure, but in Hettinger's own words "whenever you have a constructor war, everyone should get their wish". People that want a counting constructor have that,
> people that want the ability to initialize values don't have that.

Sorry Abe, but you're twisting my words and pushing very hard for a proposal that doesn't make sense and isn't necessary.

* Counts initialized to zero:   This isn't necessary.  The whole point of counters is that counts default to zero without pre-initialization.

* Counts initialized to one:  This is already done by the regular constructor.  Use "Counter(keys)" if the keys are known to be unique and "Counter(set(keys)" to ignore duplicates.

        >>> Counter('abc')
        Counter({'a': 1, 'b': 1, 'c': 1})
        >>> Counter(set('abbacac'))
        Counter({'a': 1, 'b': 1, 'c': 1})

* Counts initialized to some other value:  That would be an unusual thing to do but would be easy with the current API.

        >>> Counter(dict.fromkeys('abc', 21))
        Counter({'a': 21, 'b': 21, 'c': 21})

* Note, the reason that fromkeys() is disabled is that it has nonsensical or surprising interpretations:

        >>> Counter.fromkeys('aaabbc', 2)          # What should this do that doesn't surprise at least some users?

* That reason is already shown in the source code.

        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.')

> Obviously, Python breaks SOLID principals successfully all over the place for pragmatic reasons.
> I don't think this is one of those cases.

No amount of citing generic design principles will justify adding an API that doesn't make sense.  

Besides, any possible use cases already have reasonable solutions using the existing API.  That is likely why no one has ever requested this behavior before.

Based on what I've read in this thread, I see nothing that would change the long-standing decision not to have a fromkeys() method for collections.Counter.  The original reasoning still holds.


More information about the Python-ideas mailing list