How to do *args, **kwargs properly
Max M
maxm at mxm.dk
Tue Oct 11 07:55:44 EDT 2005
Lasse Vågsæther Karlsen wrote:
> I must be missing something but what is the proper way to do a function
> using such arguments ?
> - ability to take an unspecified number of "positional arguments"
You should probably pass a sequence to the method instead. You can do it
the other way, but it's poor coding style in most cases.
> - ability to take optional named arguments that follows the first arguments
Setting the default value to a value that cannot exist as an argument is
the normal way. Eg. None.
def fn(vals, cmp=None)
> - raise appropriate errors if I use the wrong named arguments
def fn(*values, cmp=None):
if cmp is None:
raise TypeError, "'%s' is an invalid keyword argument for this
function" % key
If you insist on doing it the other way:
FN_LEGAL_ARGS = set( ('cmp',) )
def fn(*values, **options):
for key in options.keys():
if not key in FN_LEGAL_ARGS:
raise TypeError, "'%s' is an invalid keyword argument for
this function" % key
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
More information about the Python-list
mailing list