Skip to content

Lesson 12 of 52Functions

Arguments, *args and **kwargs

Use positional, keyword and default arguments, avoid the mutable default trap, and accept any number of arguments.

20 min read0/6 questions

Open any real Python library and the function signatures look like def request(method, url, *, timeout=None, **kwargs). Every part of that is doing a job: forcing clarity, giving sensible defaults, passing options through. This lesson teaches you to read and write signatures like that, and covers the mutable default argument bug, which is probably the single most famous Python interview gotcha.

Positional and keyword arguments

When you call a function, you can pass arguments in two ways:

  • Positional: matched to parameters by position. book("Ada", 2).
  • Keyword: matched by name. book(name="Ada", seats=2). Order no longer matters.
Python
def book(name, seats, window): return f"{name}: {seats} seat(s), window={window}" print(book("Ada", 2, True))print(book(seats=2, window=False, name="Sam"))print(book("Priya", window=True, seats=1))
Output
Press Run (⌘ Enter) to see what happens.

You can mix them, but positional arguments must come first. book(name="Ada", 2, True) is a SyntaxError. Keyword arguments make calls self-documenting: book("Leo", 1, True) leaves the reader guessing what True means; window=True does not.

Default values

A parameter can have a default, used when the caller leaves it out. Parameters with defaults must come after those without.

Python
def greet(name, greeting="Hello", punctuation="!"): return f"{greeting}, {name}{punctuation}" print(greet("Ada"))print(greet("Sam", "Hi"))print(greet("Priya", punctuation="?"))
Output
Press Run (⌘ Enter) to see what happens.

Notice the last call: keywords let you skip greeting and set only punctuation.

The mutable default trap

Here is the bug. Read it, predict it, then run it.

Python
def add_tag(tag, tags=[]): tags.append(tag) return tags print(add_tag("python"))print(add_tag("web")) # surprise!
Output
Press Run (⌘ Enter) to see what happens.

The default value is created once, when the def statement runs, and stored on the function. It is not re-created on each call. So every call that relies on the default shares the very same list.

One default list, shared by every call
def add_tag(tag, tags=[]): ...
NamesObjects in memoryadd_tag defaultlist[]

Running def creates the function and evaluates [] right now, once. The function keeps that list as its default.

1/3

The fix is to use None as the default (it is immutable, so sharing it is harmless) and create a fresh list inside the function:

Python
def add_tag(tag, tags=None): if tags is None: tags = [] tags.append(tag) return tags print(add_tag("python"))print(add_tag("web"))
Output
Press Run (⌘ Enter) to see what happens.

The rule: never use a mutable value (list, dict, set) as a default. Immutable defaults like 0, "", None or a tuple are fine.

Quick check
What is printed the second time?
def add(x, items=[]):
  items.append(x)
  return items
add(1)
print(add(2))
Need a nudge? A hint rules out a wrong answer.

*args: any number of positional arguments

Sometimes you do not know how many arguments will come. A parameter written *args collects all extra positional arguments into a tuple. The name args is only a convention; the * is what matters.

Python
def total(*prices): print("got", prices) return sum(prices) print(total(4, 10, 3))print(total())print(max(3, 9, 2)) # built-ins like max and print work this way too
Output
Press Run (⌘ Enter) to see what happens.

**kwargs: any number of keyword arguments

**kwargs collects all extra keyword arguments into a dict, mapping each name to its value.

Python
def make_user(name, **details): user = {"name": name} user.update(details) return user print(make_user("Ada", role="admin", active=True))print(make_user("Sam"))
Output
Press Run (⌘ Enter) to see what happens.

You will see **kwargs a lot in wrappers that pass options through to another function untouched.

Predict the outputPython

What does this print?

def f(a, b=2, *args, c, **kwargs):
  print(a, b, args, c, kwargs)

f(1, 3, 4, 5, c=6, d=7)
Need a nudge? Hints walk you through it.

Keyword-only and positional-only parameters

You can force callers to use names, or forbid them, with two markers:

  • Parameters after a bare * are keyword-only.
  • Parameters before a / are positional-only (Python 3.8+).
Python
def connect(host, port, /, *, timeout=5.0, retries=3): return f"{host}:{port} timeout={timeout} retries={retries}" print(connect("db.local", 5432, timeout=2.0)) try: connect("db.local", 5432, 2.0) # timeout must be namedexcept TypeError as err: print("TypeError:", err)
Output
Press Run (⌘ Enter) to see what happens.

Why bother? Keyword-only parameters stop mistakes like connect("db", 5432, 2.0, 1) where nobody can tell which number is which. Positional-only parameters let a library rename a parameter later without breaking callers, which is why many built-ins use them (len(obj, /)).

Put it in order5 steps

Put the parts of a full Python signature in the order they must appear.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Unpacking at the call site

The stars also work in the other direction. When calling a function, * spreads a list or tuple into positional arguments, and ** spreads a dict into keyword arguments.

Python
def book(name, seats, window): return f"{name}: {seats} seat(s), window={window}" args = ["Ada", 2, True]print(book(*args)) options = {"name": "Leo", "seats": 1, "window": False}print(book(**options)) point = (3, 4)print(*point) # same as print(3, 4)
Output
Press Run (⌘ Enter) to see what happens.
Match the pairs0/5 matched

Match each piece of syntax to what it does.

Choose an item, then its match on the other side.

How Python binds a call

When you call a function, Python matches arguments to parameters in a fixed sequence. Knowing it lets you read any TypeError about arguments and know exactly which rule fired.

Binding f(1, 2, 3, c=4, d=5) to def f(a, /, b, *args, c, **kwargs)
  1. 1. Positionals fill slots left to righta=1, b=2
  2. 2. Extra positionals go to *argsargs=(3,), or TypeError if there is no *args
  3. 3. Keywords fill named slotsc=4; a positional-only name is skipped
  4. 4. Unknown keywords go to **kwargskwargs={'d': 5}, or TypeError if there is no **kwargs
  5. 5. Defaults fill what is leftany slot still empty with no default: TypeError

Positional arguments take parameter slots in order. 1 goes to a, 2 goes to b.

1/5

Each rule has its own error message, so the message tells you which step failed. The fourth step has a useful twist: a positional-only parameter's name is free to appear in **kwargs.

Python
def f(a, /, b, *, c=0, **rest): print(a, b, c, rest) f(1, 2, a=9, d=4) # a=9 does not clash: a is positional-only
Output
Press Run (⌘ Enter) to see what happens.

That is why functions that accept arbitrary keyword names, like a template renderer, make their own parameters positional-only. Without the /, a caller who passes a key that happens to match a parameter name gets a confusing error:

Python
def render(template, /, **context): return template.format(**context) print(render("{template} by {name}", template="Dune", name="Herbert")) def render_bad(template, **context): return template.format(**context) try: render_bad("{template}", template="Dune")except TypeError as err: print("TypeError:", err)
Output
Press Run (⌘ Enter) to see what happens.

Forwarding *args, **kwargs in wrappers

The most common real use of both stars together is forwarding: a wrapper receives whatever the caller passed and hands it, untouched, to another function. Logging, timing, retry and caching wrappers all look like this, and so do subclasses that pass options up with super().__init__(**kwargs).

Python
import functoolsimport inspect def fetch(url, *, timeout=5.0, retries=3): return f"GET {url} timeout={timeout} retries={retries}" def logged_bare(fn): def wrapper(*args, **kwargs): print("calling", fn.__name__, args, kwargs) return fn(*args, **kwargs) return wrapper def logged(fn): @functools.wraps(fn) def wrapper(*args, **kwargs): print("calling", fn.__name__, args, kwargs) return fn(*args, **kwargs) return wrapper bare = logged_bare(fetch)good = logged(fetch) print(bare.__name__, inspect.signature(bare))print(good.__name__, inspect.signature(good))print(good("/users", timeout=1)) try: good("/users", timout=1) # typoexcept TypeError as err: print("TypeError:", err)
Output
Press Run (⌘ Enter) to see what happens.

Three things to notice.

First, the bare wrapper loses the signature. Its name is wrapper and its parameters are (*args, **kwargs), so help(), your editor's autocomplete and any tool that inspects parameters (FastAPI does this to build its request parsing) see nothing useful. functools.wraps copies the name and docstring and sets __wrapped__, which inspect.signature follows back to the real function. You will build this properly in Decorators.

Second, forwarding is lazy about errors. The typo timout=1 passes straight through the wrapper and only fails when fetch itself is called. With one layer that is fine. With five layers of wrappers, the traceback points at the bottom and you have to work out where the bad argument came from.

Third, type checkers cannot see through *args, **kwargs on their own. A wrapper typed as Callable[..., Any] makes every call to the wrapped function unchecked. The fix is ParamSpec, covered in Typing Patterns for Real Code.

A few rules keep forwarding code honest:

  • Do not copy defaults into the wrapper. If fetch changes its default timeout, a wrapper that also says timeout=5.0 silently overrides it.
  • If the wrapper needs one option, take it by name and forward the rest: def wrapper(*args, verbose=False, **kwargs). The wrapper's own option never reaches the inner function.
  • Do not mutate kwargs you did not create in a way the caller can see. kwargs is a fresh dict per call, so kwargs.pop("x") is safe, but a dict you received as a plain argument is not yours to change.

Typing **kwargs with Unpack[TypedDict]

Annotating **kwargs has a catch. **kwargs: int does not mean "kwargs is an int". It means each value is an int, so the dict is dict[str, int]. Most real options are mixed types, which used to force **kwargs: Any and threw away all checking.

Since Python 3.12 (and earlier through typing_extensions), you can describe the exact keys with a TypedDict and Unpack:

client.py
from typing import NotRequired, TypedDict, Unpack
 
class RequestOptions(TypedDict):
    timeout: NotRequired[float]
    retries: NotRequired[int]
    headers: NotRequired[dict[str, str]]
 
def get(url: str, **options: Unpack[RequestOptions]) -> str:
    return send("GET", url, **options)
 
def post(url: str, body: bytes, **options: Unpack[RequestOptions]) -> str:
    return send("POST", url, body=body, **options)
 
get("/users", timeout=2.0)       # OK
get("/users", timout=2.0)        # checker error: unexpected keyword "timout"
get("/users", retries="3")       # checker error: str is not int

This is how you share one set of options across many functions without repeating a long keyword-only signature on each. At runtime nothing changes: annotations are not enforced, so the checks only happen in your editor and in CI with a checker such as mypy or pyright. TypedDict itself, including Required, NotRequired and ReadOnly, is covered in Typing Patterns for Real Code.

API design: the boolean-flag smell

Here is a call from a real code review: export(rows, True, False, ";"). Nobody can read that. Three habits fix most signature problems like it.

Make flags keyword-only. Put a bare * before any boolean or tuning option. The call becomes export(rows, header=True, quote=False, separator=";"), which documents itself, and you can add or reorder options later without breaking anyone.

Prefer explicit keyword-only parameters over **options. A function that reads its settings from **kwargs with .get() accepts typos silently, because every key is "allowed":

Python
def export_loose(rows, **options): sep = options.get("separator", ",") header = options.get("header", True) return ("h\n" if header else "") + sep.join(rows) def export(rows, *, separator=",", header=True): return ("h\n" if header else "") + separator.join(rows) print(repr(export_loose(["a", "b"], seperator=";"))) # typo, silently ignored try: export(["a", "b"], seperator=";")except TypeError as err: print("TypeError:", err)
Output
Press Run (⌘ Enter) to see what happens.

The loose version used the default comma and nobody noticed. The strict version fails at the call site with a suggestion. Use **kwargs when you genuinely forward to something else, not as a lazy way to declare options.

A boolean that changes what the function does is often two functions. load(path, as_json=True) that returns a dict or a string depending on the flag is harder to type and test than load_json(path) and load_text(path). If there are more than two modes, take an enum instead of several booleans that can contradict each other (see Enums). A flag is fine when it tweaks behaviour, like reverse=True, rather than switching to a different job.

Predict the outputPython

What does this print?

def connect(host, *, timeout=5, **extra):
  return timeout, extra

print(connect("db", timout=1))
Need a nudge? Hints walk you through it.

Reading real standard library signatures

Signatures in the docs and in help() use exactly the syntax from this lesson. Once you can decode them, the docs answer most questions about how to call something.

Python
import inspect for fn in (sorted, print, len, divmod, dict.get, str.split): print(f"{fn.__qualname__}{inspect.signature(fn)}")
Output
Press Run (⌘ Enter) to see what happens.

Read them one at a time:

  • sorted(iterable, /, *, key=None, reverse=False): the input is positional-only, and both options are keyword-only. sorted(xs, len) is an error; you must write key=len.
  • print(*args, sep=' ', end='\n', file=None, flush=False): any number of values, and every option after *args is automatically keyword-only.
  • len(obj, /) and divmod(x, y, /): positional-only, so the C code never has to accept names.
  • dict.get(self, key, default=None, /): d.get("k", 0) works, but d.get("k", default=0) raises TypeError. This surprises people.
  • str.split(self, /, sep=None, maxsplit=-1): here the options are normal parameters, so "a b c".split(None, 1) and "a b c".split(maxsplit=1) both work.

Some built-ins, like max, have no single signature at all, because they accept either one iterable or several values. Their docs show two forms: max(iterable, *, key=None) and max(arg1, arg2, *args, key=None).

Quick check
The docs say sorted(iterable, /, *, key=None, reverse=False). Which call is valid?
Need a nudge? A hint rules out a wrong answer.
ChallengeEasy

Average of anything

Write average(*nums) that accepts any number of positional arguments and returns their average as a float. With no arguments, return 0.0.

average(1, 2, 3)  →  2.0
average(1, 2)     →  1.5
average()         →  0.0
Python
def average(*nums: float) -> float: # nums is a tuple of everything that was passed pass
ChallengeMedium

Fix the shared default

add_item(item, items) appends item to items and returns the list. If no list is passed, it should start a fresh empty list every time.

The obvious version, def add_item(item, items=[]), has a bug: every call without a list shares the same one.

add_item("a")   # ['a']
add_item("b")   # should be ['b'], the buggy version gives ['a', 'b']

Write a version that works. If a list is passed, append to that exact list.

Python
def add_item(item, items=[]): # The [] above is created once and shared. Use a different default. pass
Key terms
keyword argument
An argument passed by name, f(x=1). Order does not matter, and it documents the call.
default value
Used when the caller omits the argument. Evaluated once, when def runs.
mutable default
A list/dict/set default shared across calls. Use None and create the object inside.
*args
Collects extra positional arguments into a tuple.
**kwargs
Collects extra keyword arguments into a dict.
keyword-only parameter
A parameter after * or *args; it can only be passed by name.
positional-only parameter
A parameter before /; it cannot be passed by name, so its name is free to appear in **kwargs.
forwarding
A wrapper accepting *args, **kwargs and passing them unchanged to another function.
Unpack[TypedDict]
An annotation that gives each key in **kwargs its own name and type for the type checker.