6.7.2 Keyword Arguments
Functions can also be called using
keyword arguments of the form ‘keyword = value’. For
instance, the following function:
def parrot(voltage, state='a stiff', action='voom',
print "-- This parrot wouldn't", action,
print "if you put", voltage, "Volts through it."
print "-- Lovely plumage, the", type
print "-- It's", state, "!"
could be called in any of the following ways:
parrot(action = 'VOOOOOM', voltage = 1000000)
parrot('a thousand', state = 'pushing up the daisies')
parrot('a million', 'bereft of life', 'jump')
but the following calls would all be invalid:
parrot() # required argument missing
parrot(voltage=5.0, 'dead') # non-keyword argument
# following keyword
parrot(110, voltage=220) # duplicate value for
parrot(actor='John Cleese') # unknown keyword
In general, an argument list must have any positional arguments
followed by any keyword arguments, where the keywords must be chosen
from the formal parameter names. It's not important whether a formal
parameter has a default value or not. No argument may receive a
value more than once -- formal parameter names corresponding to
positional arguments cannot be used as keywords in the same calls.
Here's an example that fails due to this restriction:
>>> def function(a):
>>> function(0, a=0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: keyword parameter redefined
When a final formal parameter of the form
present, it receives a dictionary containing all keyword arguments
whose keyword doesn't correspond to a formal parameter. This may be
combined with a formal parameter of the form
*name (described in the next subsection) which receives a
tuple containing the positional arguments beyond the formal parameter
*name must occur before
For example, if we define a function like this:
def cheeseshop(kind, *arguments, **keywords):
print "-- Do you have any", kind, '?'
print "-- I'm sorry, we're all out of", kind
for arg in arguments: print arg
keys = keywords.keys()
for kw in keys: print kw, ':', keywords[kw]
It could be called like this:
cheeseshop('Limburger', "It's very runny, sir.",
"It's really very, VERY runny, sir.",
sketch='Cheese Shop Sketch')
and of course it would print:
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
Note that the
sort() method of the list of keyword argument
names is called before printing the contents of the
dictionary; if this is not done, the order in which the arguments are
printed is undefined.