Checking for invalid keyword arguments?

Peter Abel PeterAbel at gmx.net
Mon Sep 29 16:12:39 EDT 2003


Roy Smith <roy at panix.com> wrote in message news:<roy-B6EED5.17061128092003 at reader2.panix.com>...
> 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?

One solution - which reminds me of *slots* -
could be the following:

>>> def fn(**kwa):
... 	allowed='conversion drop some_thing else'.split()
... 	not_used   =filter(lambda var:var not in kwa,allowed)
... 	not_allowed=filter(lambda var:var not in allowed,kwa)
... 	print 'not_allowed:\t'+'\n\t\t'.join(not_allowed)
... 	print 'not_used   :\t'+'\n\t\t'.join(not_used)
... 
>>> fn(drop=1,conversion=True,foo=5, false=False)
not_allowed:	false
		foo
not_used   :	some_thing
		else
>>> 

Regards
Peter




More information about the Python-list mailing list