Python args and kwargs

Python args and kwargs #

*args #

Allows for a flexible number of arguments in a function.

Example: a simple function to add up some numbers:

def add_numbers(*args):
    return sum(args)

print(add_numbers(1, 2, 3, 4, 5))

**kwargs #

Allows for a flexible number of keyword arguments in a function.

Where keyword in this case is a keyword with assignment.

def print_into(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(
    name = "Arnold",
    age = 10
)

Note that **kwargs is just by convention. It could be anything. Such as **k.

Combined #

*args and **kwargs can be combined within a single function.

def combined_function(*args, **kwargs):
    print("args:", args)
    print("kwargs:", kwargs)

combined_function(
    1, 2, 3,
    name = "Arnold",
    age = 10
)