PEP 322: Reverse Iteration (REVISED, please comment)
aleaxit at yahoo.com
Thu Nov 6 08:27:01 CET 2003
Michele Simionato wrote:
> So, only summing strings is disallowed, all the rest is allowed, but
> there can be performance traps, for instance in summing lists. So, if
> 'sum' is only good at summing numbers, why this is not enforced?
How? Sure, we could specialcase lists and tuples and array.array's
and Numeric.array's and ... -- but that wouldn't really be right either:
e.g. with tuples you can't do much better _easily_ (turning each into
a list and doing a loop of extend isn't "easily" -- it's only warranted in
some cases). Basically, sum is fine whenever the alternative is
reduce(operator.__add__ ... or a loop of
for item in sequence: result = result + item
since it's defined to have exactly that semantics. Problem is mainly
with cases in which we'd rather do
for item in sequence: result += item
which is slightly different semantics when result is mutable; or more
specialized cases such as ''.join(sequence).
> We are forbidden to sum strings, but then for the same reason we
> should be forbidden to sum lists: there is some inconsistency here ...
> care to explain the rationale for 'sum' again ?
sum is basically to sum numbers. But in Python there's no way to tell
precisely what IS "a number". We've special-cased strings because
we _know_ people desperately want to sum bunches of them all of
the time -- my original approach was to have sum detect the case and
delegate to ''.join, but Guido thought that weakened sum's specificity
to numbers and had me forbid it instead. I've recently proposed going
for the performance trap by redefining the semantics as a loop of += --
but Guido isn't happy with that (user-visible change, some way or other,
at least for sufficiently weird user-coded objects). I've also proposed
adding optional abstract baseclasses similar to basestring to give various
spots in Python a chance to detect "this user type is meant to be a
number [it inherits from basenumber] / a sequence [from basesequence] /
and so on", but again I've mostly seen reluctance about this on python-dev.
So the issue is a bit in the air (for Python 2.4).
More information about the Python-list