Suppose we have a function:
>>> def hypothenuse(x, y): ... return math.sqrt(x**2 + y**2) ...
When calling it, we can specify the arguments in order:
>>> hypothenuse(1,2) 2.2360679774997898
or we can specify the arguments explicitly by names like this:
>>> hypothenuse(x=1, y=2) 2.2360679774997898 >>> hypothenuse(y=2, x=1) 2.2360679774997898
This way of specifying arguments is called keyword arguments.
Keyword arguments must appear after all non-keyword arguments.
REXML could not parse this XML/HTML: <pre title="interpreter"> >>> hypothenuse(1, y=2) 2.2360679774997898 >>> hypothenus(y=2, 1) File "<stdin>", line 1 SyntaxError: non-keyword arg after keyword arg </pre>
Keyword arguments are very convenient when there are a lof of optional arguments.
>>> def foo(a=1, b=2, c=3, d=5, e=5): ... print a ... print b ... print c ... print d ... print e ... >>> foo() 1 2 3 5 5 >>> foo(b=7) 1 7 3 5 5 >>> foo(c=8, e=16) 1 2 8 5 16
We can write a function that takes a variable number of keyword arguments. When writing such a function, add two starts (**
) in front of the last variables.
>>> def bar(a, b, **kwargs): ... print a ... print b ... print kwargs ... >>> bar(1, 2, xyz=10, pqr=20, mon=9) 1 2 {'xyz': 10, 'pqr': 20, 'mon': 9} >>> bar(a=9, b=2, c=5, d=7, e=8, f=-1) 9 2 {'c': 5, 'e': 8, 'd': 7, 'f': -1}
Notice that the argument with two stars becomes a dictionary that holds all keyword arguments that do not refer to other parameters of the function.
Notice also that the keys in the dictionary are strings that you specify as names of keyword arguments.