sum and strings

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Fri Aug 25 00:19:26 EDT 2006


On Thu, 24 Aug 2006 18:24:19 +0200, Fredrik Lundh wrote:

> besides, in all dictionaries I've consulted, the word "sum" means 
> "adding numbers".  are you sure it wouldn't be more predictable if "sum" 
> converted strings to numbers ?

And then on Thu, 24 Aug 2006 19:12:17 +0200 Fredrik also wrote:

> (and note that the python-dev consensus is that sum is for numbers and
> join is for strings.  anyone who cares about writing readable code knows
> that names matter; different things should have different names.)

And yet sum() sums lists, tuples, custom classes, and many other things
which are not numbers. Did python-dev not notice this? I doubt it.

I've read all the arguments in favour of type-checking the arguments to
sum() (actually only the second argument). I'm not convinced that this
case is special enough to break the rules by raising an exception for
strings. (Insert usual arguments about consistency, duck typing, least
surprise, etc.)

There is an alternative: raise a warning instead of an exception. That
permits the admirable strategy of educating users that join() is
generally a better way to concatenate a large number of strings, while
still allowing programmers who want to shoot themselves in the foot to do
so. Python generally allows the programmer to shoot himself in the foot,
if the programmer insists, e.g. private attributes are by convention, not
enforced by the language. That's one of the nice things about the
language: it *suggests* what to do, but doesn't *insist* it knows what you
want better than you do.



-- 
Steven D'Aprano 




More information about the Python-list mailing list