This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 4: More functions

Arbitrary number of keyword arguments

face Josiah Wang

Let’s say that you are allowing users to enter lots of keyword arguments. This might start to become hard to manage!

def customise_page(background="white", width=500, height=1000, avatar=None,
        title="Title", subtitle="", author="", year=None, font_size="24", 
        font_face="Arial", text_color="black"):
    pass

To make this more manageable, you can use double asterisks (**) to take in an arbitrary number of keyword arguments. This time, you will end up with a dict containing (key, value) pairs provided by the user. You can then process these pairs as needed (perhaps you can have a separate function called parse_args() to handle these in a modular way).

def customise_page(**kwargs):
    parse_args(kwargs)

def parse_args(options):
    for key, value in options.items():
        if key == "background":
            set_background(value)
        elif key == "width":
            set_width(value)
        elif key == "avatar":
            set_avatar(value)
        else:
            print(f"Unknown keyword {key}.")
            return

customise_page(background="red", width=500, avatar="selfie.jpg")