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

Tim Peters tim.peters at gmail.com
Wed Apr 18 17:39:47 EDT 2018


[Tim]
>> (*) The obvious implementation:
>>
>>      def __mul__(self, other):
>>         if isinstance(other, Sized):
>>             raise TypeError("cannot multiply Counter by Sized type %s" % type(other))

[Serhiy]
> Wouldn't be better to return NotImplemented here?

Probably, but that's up to Raymond.  What I like about the above is
that the error message is very explicit about why the argument was
rejected.  A generic, e.g.,

    TypeError: unsupported operand type(s) for *: 'Counter' and 'generator'

isn't as informative.

OTOH, ya, it's better practice to give other.__rmul__ a chance at it.


>>          result = Counter()
>>          for k, v in self.items():
>>              result[k] = v * other
>>          return result

> If discard non-positive values, this will automatically make multiplying
> Counter by Counter (or by sequence) invalid, because they are not comparable
> with 0.
>
>          for k, v in self.items():
>              v = v * other
>              if v > 0:
>                  result[k] = v * other

I'd start to buy that only if you promised to answer all Stackoverflow
questions of the form:

    Hey, I tried multiplying two Counters and got

    TypeError: '>' not supported between instances of 'Counter' and 'int'

    What the hell is that supposed to mean?

;-)


More information about the Python-ideas mailing list