How to do *args, **kwargs properly

Lasse Vågsæther Karlsen lasse at vkarlsen.no
Tue Oct 11 13:37:57 CEST 2005


I must be missing something but what is the proper way to do a function 
using such arguments ?

Specifically I'm looking for:

- ability to take an unspecified number of "positional arguments"
- ability to take optional named arguments that follows the first arguments
- raise appropriate errors if I use the wrong named arguments

for instance:

fn(1, 2, 3)
fn(1, 2, 3, cmp=lambda x, y: y-x)
fn(1, 2, 3, cpm=lambda x, y: y-x) # TypeError on this

Is the following the way to go ?

def fn(*values, **options):
     comparison = cmp
     for key, value in options.iteritems():
         if key == "cmp":
             comparison = value
         else:
             raise TypeError, "'%s' is an invalid keyword argument for 
this function" % key
     # rest of function here

or is the "proper python" way simply this:

def fn(*values, **options):
     if "cmp" in options: comparison = options["cmp"]
     else: comparison = cmp
     # rest of function here

and thus ignoring the wrong parameter names?

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:lasse at vkarlsen.no
PGP KeyID: 0x2A42A1C2



More information about the Python-list mailing list