Chapter 7: Functions

Keyword arguments

face Josiah Wang

Here is our function definition again.

def do_something(a, b, c=2, d="great", e=5, f="john", g="python", h=-1, i=0, j=[]):
    print(f"{a}; {b}; {c}; {d}; {e}; {f}; {g}; {h}; {i}; {j}")
    return None

Apart from positional arguments, a caller can also use keyword arguments to supply the arguments for these optional parameters without worrying about the positioning of the parameter. The caller can skip any optional parameters arbitrarily.

>>> x = do_something("first", "second", i=2, f="josiah")
first; second; 2; great; 5; josiah; python; -1; 2; []

Note that the caller must provide the (mandatory) positional arguments first before supplying any keyword arguments. It is obvious why if you think about it for a bit - Python will be completely confused when trying to match the parameters to the argument otherwise!

>>> x = do_something(d="no good", "first", "second") 
  File "<stdin>", line 1
SyntaxError: positional argument follows keyword argument

Using keyword arguments in your function calls can potentially improve the readability of your code. Compute the two function calls below. They both do the same thing, but which one do you find is more self-explanatory and easier to understand?

robot = generate_robot(3, 6, "joy", 100, 200, True)

robot = generate_robot(x=3, y=6, message="joy", width=100, height=200, random=True)