Advanced Python · 18 min

Unpack values and forward arguments

Use destructuring, enumerate, and flexible arguments without losing readability.

Jump to the automation lab

Tuple unpacking binds each item to its own name. With enumerate(items, start=1), each iteration produces a pair of the index and item, which you can unpack in the loop header.

In a call, *items expands an iterable into positional arguments and **options expands a mapping into keyword arguments. In a function definition, *args collects extra positional arguments into a tuple and **kwargs collects extra keywords into a dictionary.

Name the parameters your callers use regularly. Pack and forward arguments when wrapping a function, while keeping the common calls easy to read.

Follow the example

The list holds two positional values.

Worked examples

Forward keyword arguments through a wrapper

The wrapper accepts the same positional and keyword arguments, then passes them to the original function.

forward.py
def total(*values, start=0):
    return start + sum(values)

def logged_call(function, *args, **kwargs):
    result = function(*args, **kwargs)
    print(f"Result: {result}")
    return result

logged_call(total, 2, 3, start=10)  # Result: 15

Run the example and practice

Number the lines starting at 1. Keep support for any number of items and for a custom prefix.

Target output

Tree 1: oak
Tree 2: elm
Show a hint

Unpack number and item from enumerate(items, start=1) in the comprehension.

Output

Ready

Run your code to see the output here.

Check output also tests your code with additional cases.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
def render(*items, prefix="Item"):
    return [f"{prefix} {number}: {item}" for number, item in enumerate(items, start=1)]

values = ["oak", "elm"]
style = {"prefix": "Tree"}
print("\n".join(render(*values, **style)))

Automation lab

Format spreadsheet cells as table rows

Unpack each exported row as positional arguments and reuse a separator setting for the whole table.

Output

Ready

Run the example to see the output here.

Add an extra column to both rows and change the separator in one place.

Further reading in Automate the Boring Stuff with Python by Al Sweigart