[Python-ideas] collections.Counter should implement __mul__, __rmul__

Tim Peters tim.peters at gmail.com
Wed Apr 18 15:42:25 EDT 2018


[Wes Turner <wes.turner at gmail.com>]
> The use cases these TypeErrors would exclude include weightings (whether
> from a generator without an intermediate tuple/list or from a dict) where
> the need is to do elementwise multiplication:

Yes.  That's exactly what I had in mind when I wrote:

>> What we're trying to stop is things like "Counter * Counter" for now,
>> because the obvious implementation(*) of Counter.__mul__ would do a
>> strange thing with that, where a quite different thing is plausibly
>> wanted (and may - or may not - be added later - but, due to backward
>> compatibility, cannot be added later if the initial implementation
>> does the strange thing).

The obvious implementation (already given (*)) of Counter.__mul__
would NOT AT ALL do elementwise multiplication.  Nobody has asked for
that yet either, so nobody is proposing to add it now either.  But
it's predictable that someone _will_ ask for it when __mul__ is
defined for "scalars".  It may or may not be added at that time.  But
it will be flat-out impossible to add it later (because of backward
compatibility) _if_ the initial implementation does something entirely
different.  So, at first, we want to raise an exception for a
non-'scalar" argument, so that it remains _possible_ to do something
sane with it later.

...

>> (*) The obvious implementation:
>>
>>     def __mul__(self, other):
>>        if isinstance(other, Sized):
>>            raise TypeError("cannot multiply Counter by Sized type %s"
>> % type(other))
>>         result = Counter()
>>         for k, v in self.items():
>>             result[k] = v * other
>>         return result


More information about the Python-ideas mailing list