How to do *args, **kwargs properly

Alex Martelli aleax at mail.comcast.net
Tue Oct 11 07:47:27 EDT 2005


Lasse Vågsæther Karlsen <lasse at vkarlsen.no> wrote:
   ...
> 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

I assume these are your specs.

> 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?

Errors should not pass silently, unless explicitly silenced.

So, I would code:

def fn(*values, **opts):
  cmp = opts.pop('cmp', cmp)
  if opts: raise ValueError, 'Unknown option(s): %s' % opts.keys()
  # rest of function here

There are some cases where ignoring extra options, or just warning about
them, may be more appropriate, but normally I would check...


Alex



More information about the Python-list mailing list