Checking for invalid keyword arguments?
Oren Tirosh
oren-py-l at hishome.net
Mon Sep 29 06:42:05 EDT 2003
On Sun, Sep 28, 2003 at 05:06:11PM -0400, Roy Smith wrote:
> I've got a function that takes a couple of optional keyword arguments.
> I want to check to make sure I didn't get passed an argument I didn't
> expect. Right now I'm doing:
>
> conversion = None
> drop = False
> for key, value in kwArgs.items():
> if key == 'conversion':
> conversion = value
> elif key == 'drop':
> drop = value
> else:
> raise TypeError ('Unexpected keyword argument %s' % key)
>
> which seems kind of verbose. Is there a neater way to do this check?
Python's built-in default argument mechanism does exactly that:
def f(conversion=None, drop=False, ...):
...
I assume that you have some good reason for using kwargs instead such as
passing a bunch of arguments together as a dict but you can unpack this
bunch by calling another function:
def f(**kwargs):
def f2(conversion=None, drop=False):
...
return f2(**kwargs)
Oren
More information about the Python-list
mailing list