Variable arguments in Python

When looking at some built-in functions within builtins.py, I came across the strange syntax

def ascii(*args, **kwargs): 

The *args and **kwargs has a special meaning within Python. The *args will give all function parameters as a tuple and the **kwargs will give a dictionary of key/values.

Note: convention seems to suggest the parameter names args and kwargs, but these are not enforced naming conventions.

Let’s see these two (separately) in action

def show_args(*args):
    for a in args:
        print(a)


def show_key_values(**kwargs):
    for a in kwargs:
        print(a, kwargs[a])


show_args("Hello", "World", 123)
show_key_values(first="Hello", second="World", third=123)

As you can see, in the show_args function we will list each argument out, hence the output to stdout will be

Hello
World
123

The show_key_values expects key/value input, hence the field/property name followed by = and then the value. This will output

first Hello
second World
third 123

In both cases we can also pass no arguments to these methods and nothing will be output, but it’s also not unusual (as can be seen by the ascii function at the start of this post) for the two pieces of syntax to be combined, i.e.

def show_args_key_values(*args, **kwargs):
    for a in args:
        print(a)

    for a in kwargs:
        print(a, kwargs[a])

and now this can be called in the following ways

show_args_key_values("Hello", "World", 123, first="Hello Again")

As you can probably tell from this syntax, you will need to list the list of arguments before the key/value list of arguments, but you can write the following

show_args_key_values("Hello")
show_args_key_values(first="World")

and therefore handle either a list of key/value set of input.