1.2.29 · D2Introduction to Programming (Python)

Visual walkthrough — ` - args` and ` - kwargs` — flexible argument passing

614 words3 min readBack to topic

We only assume one thing: you know a function is a machine you feed values into, like add(2, 3). We build the rest.


Step 1 — A function is a set of labelled buckets

WHAT. When you write def add(a, b):, you are creating two named buckets, a and b. When you call add(2, 3), Python pours the values into the buckets left to right: 2 into a, 3 into b.

WHY start here. Everything that follows is the same pouring idea — we're just going to add a special bucket that can hold any amount. To see why that's useful, first feel the rigidity: two buckets means exactly two values, no more, no less.

PICTURE. The call values (top) fall into exactly the buckets that match by position.

Figure — ` - args` and ` - kwargs` — flexible argument passing
Caption: the call add(2, 3) at the top; an arrow carries 2 down into a bucket labelled a and 3 down into a bucket labelled b. Below, a red note reminds us add(2, 3, 4) has no third bucket and raises TypeError.

Read that line in plain words: the machine add receives 2 (which flows to bucket a) and 3 (which flows to bucket b).

  • 2 — the first positional value, so it goes to the first bucket a.
  • 3 — the second positional value, goes to the second bucket b.

If you now try add(2, 3, 4), there is no third bucket for 4 to land in → Python raises TypeError. That failure is the problem *args solves.


Step 2 — The * opens a stretchy bucket

WHAT. Writing def add(*args): creates one bucket named args with a * in front. The * means: "catch every leftover positional value and stack them inside me." The stack it builds is a tuple.

WHY the * and not just another name? A plain name (args) would be one slot holding one value. The * is the operator that upgrades it into a catch-all: however many values arrive, they all fit. This is the exact tool we need for "I don't know how many inputs."

PICTURE. Three values fall, but instead of hitting three separate buckets, they all drop into one wide container and become a tuple `(2, 3