[Python-ideas] sum(...) limitation
Steven D'Aprano
steve at pearwood.info
Wed Aug 13 19:46:30 CEST 2014
On Wed, Aug 13, 2014 at 09:59:52AM -0700, Chris Kaynor wrote:
> The basic form I would use for an updated sum, which would often, but not
> always, perform better would be something like (preferably, written in C,
> not pure Python):
>
> def sum(items, start=0):
> value = copy.copy(start) # Make sure that start is not mutated.
> for item in items:
> value += item
> return value
That's a semantic change from the existing sum: start does not have
to be copyable. Currently I can write this:
py> class A:
... def __copy__(self):
... raise TypeError("I am unique!")
...
py> a = A()
py> class B:
... def __radd__(self, other):
... return 23
...
py> b = B()
py> sum([b, 1000, 2000], a)
3023
By changing the semantics of sum() to require start to be copyable,
your revision has just broken my application.
> To avoid needing to access copy.copy, something like the following would
> also work, but with a bit more local complexity:
>
> def sum(items, start=0):
> count = len(items)
That's another semantic change: sum() currently accepts iterators
(although not *infinite* iterators). This revision has now broken tens
of thousands of applications.
--
Steven
More information about the Python-ideas
mailing list