Initialization of variables using no-arg constructor

E

Edward Waugh

Consider the following (working) Python code:

import sys

def sum(list):
# total = 0 does not work for non-numeric types
total = list[0].__class__()
for v in list:
total += v
return total

l = [1, 2, 3]
print sum(l)

l = [1.1, 2.2, 3.3]
print sum(l)

l = ["a", "b", "c"]
print sum(l)

In order for sum() to be generic I initialize total to the value of
list[0].__class__(). This works but I would like to know if this is the
correct or preferred way of doing it. It means that sum() must be given a
list whose elements are types or classes that have a no-arg constructor
(through this is probably almost always the case).

Thanks,
Edward
 
P

Paul Rubin

In order for sum() to be generic I initialize total to the value of
list[0].__class__(). This works but I would like to know if this is
the correct or preferred way of doing it.

More natural would be (untested):

def sum(list):
assert list # both versions fail if list is empty
total = list[0]

# could use list[1:] but this avoids copying
for i in xrange(1, len(list)):
total += list

or various alternate spellings with iterators, the reduce function, etc.

This pattern is common enough that Haskell has a "foldl1" function
similar to reduce but initializing from the first element of the sequence.
 
J

jordanrastrick

Just to expand a little on what others have already said - not only is
the total = list[0] etc.approach more readable, idiomatic, and elegant,
IMO its more semantically correct.

Your constraint that list[0].__class__ has a no-arg constructor is not
strong enough; a more subtle and potentially bug-prone assumption youre
making is that this no-arg constructor returns an identity element
(something that when added doesnt affect your overall "total") with
respect to the addition operator. This happens to be true of summing
numbers (__class__ == 0), and concatenating strings (__class__() ==
""). But I don't think you can take this behaviour for granted from an
arbitrary class.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top