See All Titles |
![]() ![]() Keyword Variable Arguments (Dictionary)In the case where we have a variable number or extra set of keyword arguments, these are placed into a dictionary where the "keyworded" argument variable names are the keys, and the arguments are their corresponding values. Why must it be a dictionary? Because a pair of items is given for every argument—the name of the argument and its value—so it is a natural fit to use a dictionary to hold these arguments. Here is the syntax of function definitions which use the variable argument dictionary for extra keyword arguments: def function_name([formal_args,][*vargst,] **vargsd): function_documentation_string function_body_suite To differentiate keyword variable arguments from non-keyword informal arguments, a double asterisk ( ** ) is used. The ** is overloaded so it should not be confused with exponentiation. The keyword variable argument dictionary should be the last parameter of the function definition prepended with the '**'. We now present an example of how to use such a dictionary: def dictVarArgs(arg1, arg2='defaultB', **theRest): 'display 2 regular args and keyword variable args' print 'formal arg1:', dictVarArgs print 'formal arg2:', arg2 for eachXtrArg in theRest.keys(): print 'Xtra arg %s: %s' % \ (eachXtrArg, str(theRest[eachXtrArg])) Executing this code in the interpreter, we get the following output: >>> dictVarArgs(1220, 740.0, c='grail' formal arg1: 1220 formal arg2: 740.0 Xtra arg c: grail >>> >>> dictVarArgs(arg2='tales', c=123, d='poe', a='mystery') formal arg1: mystery formal arg2: tales Xtra arg c: 123 Xtra arg d: poe >>> >>> dictVarArgs('one', d=10, e='zoo', men=('freud', 'gaudi')) formal arg1: one formal arg2: defaultB Xtra arg men: ('freud', 'gaudi') Xtra arg d: 10 Xtra arg e: zoo Both keyword and non-keyword variable arguments may be used in the same function as long as the keyword dictionary is last and is preceded by the non-keyword tuple, as in the following example: def newfoo(arg1, arg2, *nkw, **kw): display regular args and all variable args' print 'arg1 is:', arg1 print 'arg2 is:', arg2 for eachNKW in nkw: print 'additional non-keyword arg:', eachNKW for eachKW in kw.keys(): print "additional keyword arg '%s': %s" % \ (eachKW, kw[eachKW]) Calling our function within the interpreter, we get the following output: >>> newfoo('wolf', 3, 'projects', freud=90, gamble=96) arg1 is: wolf arg2 is: 3 additional non-keyword arg: projects additional keyword arg 'freud': 90 additional keyword arg 'gamble': 96
|
© 2002, O'Reilly & Associates, Inc. |