[Python-ideas] Intermediate Summary: Fast sum() for non-numbers

Stefan Behnel stefan_ml at behnel.de
Thu Jul 18 18:08:56 CEST 2013


Sergey, 14.07.2013 21:26:
> It's worth to note, that sum() is one of the most commonly suggested
> options to add lists [1], despite usually someone also comes and says
> that it may be slow. This means, that people at least often try to
> use sum() for lists. That case was also explicitly mentioned in
> comments to sum() sources. So the problem is not hypothetical.

IMHO, the reason why sum() supports other input types than numbers is that
in Python 2, at the time when it was implemented, there was no clear
definition of a "number", so it was impossible to correctly distinguish
between numberish input and input that should be rejected. I guess that
explicitly rejecting arbitrary builtin types was considered overly, well,
arbitrary, so it wasn't done at the time.

If sum() was designed today, with the ABCs in Python 3 available, it would
be easy to restrict it to meaningful input types, i.e. those that declare
themselves as being numbers. However, changing this now would arbitrarily
break existing code, so it's unlikely that this will happen.

So I guess we'll just have to live with that little wart that sum() doesn't
always reject stupid input. We can still tell those who try it that what
they do is stupid, and show them better ways to do it. There were lots of
suitable examples of better code presented over the last decade or so, some
of which showed up in the recent threads again.

Stefan




More information about the Python-ideas mailing list