Initialization of variables using no-arg constructor

Ben Finney bignose+hates-spam at benfinney.id.au
Mon Oct 9 19:49:02 EDT 2006


"Edward Waugh" <edward_waugh at hotmail.com> writes:

> 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

Your function assumes that all items of the list will be compatible,
to the extent of '+', with the first item. That's a valid assumption,
but note that it's part of the interface of the function -- i.e. the
expectations of how it will be called.

    >>> l = ["a", ["spam", "eggs"], None, 4]
    >>> print sum(l)
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "<stdin>", line 5, in sum
    TypeError: cannot concatenate 'str' and 'list' objects

Since calling the function with a list containing non-numeric elements
makes no sense, why are you attempting to accommodate it?

If the function's interface is that it sums the items of the list
numerically, then assume numbers and let the function raise an
exception for the caller to handle if that's not true.

If the function's interface is to do something else, it should be made
clearer. A good start would be to name it something more descriptive
of its actual purpose than 'sum'.

-- 
 \       "What I resent is that the range of your vision should be the |
  `\                              limit of my action."  -- Henry James |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list