Checking for invalid keyword arguments?

Peter Hansen peter at
Sun Sep 28 23:57:29 CEST 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?

I'd suggest writing a general-purpose subroutine which can do the necessary 
checks for you, then use a one-liner to call it with the "pattern" you 
require.  It might look like this for the call:

   conversion, drop = checkOptArgs(kwArgs, conversion=None, drop=False)

This clearly shows the allowed keyword args, their default values, and assigns
values to the local names on return.  It can of course raise the TypeError
for you if a bad name is in kwArgs.


More information about the Python-list mailing list