[Tutor] design advice for function

Kent Johnson kent37 at tds.net
Sun Dec 18 13:31:39 CET 2005


Christopher Spears wrote:
> I got my function to work!  It takes arguments and
> adds them:
> 
> def adder(**args):
>     argsList = args.values()
>     sum = argsList[0]
>     for x in argsList[1:]:
>         sum = sum + x
>     return sum
> 
> print adder()
> 
> However, if I run the above code.  I get an error:
> 
> Traceback (most recent call last):
>     sum = argsList[0]
> IndexError: list index out of range
> 
> This is caused by the line: print adder().  Obviously
> if adder() doesn't receive any arguments, it can't
> build the lists resulting in an IndexError.  What is
> the best way to solve this?  Should I write some
> syntax into the function to check for arguments? 
> Should I just write a seperate function to check for arguments?

Actually adder is still receiving an argument, it is an empty dictionary:

  >>> def adder(**args):
  ...   print args
  ...
  >>> adder()
{}

If you iterate the whole items() list then Python will do the right thing (i.e. nothing) 
when the list is empty. Can you think of another way to initialize sum that lets you 
iterate the whole list instead of slicing off the first element?

A couple of notes:
- I'm not sure why you are passing keyword arguments, do you know that there is a way to 
pass a variable list of arguments to a function? Use a single * in the parameter list and 
unnamed arguments at the point of call. The argument list is passed as a tuple:

  >>> def adder(*args):
  ...   print args
  ...
  >>> adder()
()
  >>> adder(1, 2, 3)
(1, 2, 3)

Of course if you want the keyword style of argument passing then keep doing what you are 
doing.

- The name of the keyword parameter is conventionally something like kwds or kwargs. 
'args' is usually used for a variable argument list as in my second example. Your code may 
be easier for others to understand if you use this convention. (At least I was thrown for 
a moment by **args and read it as *args.)

Kent



More information about the Tutor mailing list