Checking for invalid keyword arguments?
Alex Martelli
aleax at aleax.it
Sun Sep 28 17:52:45 EDT 2003
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?
Sure, particularly in Python 2.3:
conversion = kwArgs.pop('conversion', None)
drop = kwArgs.pop('drop', False)
if kwArgs:
raise TypeError("Unexpected keyword args: %s" % kwArgs.keys())
The .pop method of dictionary objects, new in 2.3, removes a key from
a dict (if present), returning the corresponding value (or a supplied
default -- if key is absent and no default supplied, it raises). So,
if anything is still left in kwArgs after the two pops, we know there
were "unknown and ignored" keyword arguments in dict kwArgs.
Of course, in most cases you'd simply declare your function with:
<funcname>(<whatever other args>, conversion=None, drop=False):
and no **kwArgs, and just let Python do the checking for you. But
when the kwArgs DO have to come in a dict (as, rarely, does happen,
for a variety of peculiar reasons), the new 2.3 idiom will help.
Alex
More information about the Python-list
mailing list