sum and strings

Bryan Olson fakeaddress at nowhere.org
Fri Aug 25 05:18:18 EDT 2006


Fredrik Lundh wrote:
> [...] besides, in all dictionaries I've consulted, the word "sum"
> means "adding numbers".

That's a result of not looking deeply enough.

Fredrik Lundh is partially right, in that "Sum" usually refers
to addition of numbers. Nevertheless, the idea that "sum" must
refer to numbers is demonstrably wrong: Googling "define: sum"
shows several counter-examples, the first of which is:

     The final aggregate; "the sum of all our troubles did not
     equal the misery they suffered."

Numbers? What numbers?  Lundh may be telling the truth about
all the dictionaries he consulted, but anyone with Internet
access could have looked -- and found -- further.

Dictionary definition is not really the issue. Who could miss
the correspondence between the addition operation and the sum
function?  Why would we choose a language or type system that
cannot even make "+" and "sum" behave consistently?


>  are you sure it wouldn't be more predictable if "sum" 
> converted strings to numbers ?

Definitely reject that idea. People so misguided as to want
silent string-to-int conversion can use Perl.

The problem here is unifying the "+" operator and the "sum"
function, The former is one of Python's several 'special'
methods; the latter is one of Python's pre-defined
functions. See:

   http://docs.python.org/ref/numeric-types.html
   http://docs.python.org/lib/built-in-funcs.html

And herein is the problem: A class may implement "__add__" any
way the programmer chooses. Python should require, or at least
document requirements, on further properties of addition. Python
should insist that addition be symmetric an transitive, and
classes implementing addition provide an additive identity.


> (after all, questions about type errors like "cannot concatenate 'str' 
> and 'int' objects" and "unsupported operand type(s) for +: 'int' and 
> 'str'" are a *lot* more common than questions about sum() on string lists.)

Right.  Duck-typing can work, while sloppy typing is doomed.


-- 
--Bryan



More information about the Python-list mailing list