ᚱᛗ
© 2022
Powered by Hugo

Arbitrary Number of Arguments (*args & **kwargs)

Table of Contents

Summary

*args (positional arguments) and **kwargs (keyword arguments) are optional arguments that can be passed in a function signature or a function call. Their purpose is to allow the user to pass an arbitrary number of arguments to the function; or to reduce clutter by passing many arguments as a single object.

Note: the names—“args” and “kwargs”—are simply conventions, they are irrelevant to the functionality, which is given by the symbols * and **.

1. *args (Positional Arguments)

Arbitrary Number of Input Parameters

Let’s illustrate this feature with an example. Take the following function (notice how parameters are not defined in advance and *args has been replaced by *inputs):

def process1(*inputs):
    """Take positional arguments as input and concatenate them."""
    return " + ".join(inputs)
process1("a", "random", "number", "of", "inputs")
# 'a + random + number + of + inputs'

Reducing Clutter with a Single Object

input_tuple = ("this", "that", "the other")
process1(*input_tuple)
# 'this + that + the other'

Unpacking a function’s return directly as an argument of another function:

def process0():
    """Produce a random number of outputs from 2 to 10."""
    import random

    size = random.randint(2, 10)
    outputs = ["output" + str(_) for _ in list(range(size))]
    return outputs


process1(*process0())
# 'output0 + output1 + output2 + output3 + output4'

2. **kwargs (Keyword Arguments)

Arbitrary Number of Input Parameters

def x_power_of_n(**kwargs):
    computations = []
    for x, n in kwargs.items():
        computations.append(x + " ** " + str(n))
        # print(f"{x} ** {n}")
    return computations
x_power_of_n(element1=2, element2=5, element3=3)
# ['element1 ** 2', 'element2 ** 5', 'element3 ** 3']

Reducing Clutter with a Single Object

inputs = {"element1": 2, "element2": 5, "element3": 3}
x_power_of_n(**inputs)
# ['element1 ** 2', 'element2 ** 5', 'element3 ** 3']

Passing double kwargs in the call

def divider(numerator, denominator):
    result = numerator / denominator
    return result

kwargs1 = {"numerator": 100}
kwargs2 = {"denominator": 10}
print(divider(**kwargs1, **kwargs2))  # 10