restriction on sum: intentional bug?
python at mrabarnett.plus.com
Sun Oct 18 01:42:05 CEST 2009
Carl Banks wrote:
> On Oct 17, 2:22 pm, Alan G Isaac <alan.is... at gmail.com> wrote:
>> On 10/17/2009 7:06 AM, Carl Banks wrote:
>>> I'm basically saying here is, by shutting out strings from sum,
>>> you don't really lose much in terms of duck typing, because duck
>>> typing wouldn't have been that helpful anyway.
>> That boils down to an argument for type checking
>> whenever you cannot imagine my use case. I hope
>> you do not write your own code that way...
> No, it doesn't. It's an argument that the type check, IN THIS CASE,
> doesn't cost you much since duck typing isn't that useful here, IN
> THIS CASE, to begin with. Nothing more.
> Extrapolating this argument to be a general defense of type checking
> is something you did.
>> Here is a use case you might have ruled out with
>> that approach. A PyX `path` defines `__add__`
>> so that paths can be combined as subpaths of a
>> single path. This is **VERY USEFUL**.
>> Now if I have a list of paths, it is useful to
>> to combine them: sum(pathlst,path()).
> That's a fair counterargument. It definitely seems a lot more likely
> that some code could be written that works for a list of strings or a
> list of path components, meaning that it'd be desirable to have a
> single operation which works on both, for which sum() seems like it'd
> be a convenient candidate. Consider my argument weakened somewhat.
Here's a suggestion: add a new special method '__sum__' for summing
If 'sum' isn't given an initial value then the first value in the
sequence is used as the initial value. The (remainder of) the sequence
is passed to initial_value.__sum__ to perform the summation. If __sum__
isn't defined then the __add__ method is used repeatedly as at present.
The 'str' and 'unicode' classes (although I'd expected it would be the
'bytes' and 'str' classes in Python 3) would define __sum__ as an
efficient summation. Other classes like 'list' could do likewise.
No more special cases!
More information about the Python-list