# Positional, Default & *args / **kwargs

> Master Python flexible argument mechanisms: positional arguments, keyword arguments, *args tuple packing, **kwargs dictionary packing, keyword-only parameters, and avoiding the dangerous mutable default argument trap.

Subject: Python | Lesson 10 of 24 | 7 min read
Interactive lesson: https://codewithanimation.in/python/arguments-kwargs
Previous: [Defining Functions & Return Values](https://codewithanimation.in/python/defining-functions.md) | Next: [Variable Scope & the LEGB Rule](https://codewithanimation.in/python/scope.md)

## Flexible Function Signatures

Python provides multiple ways to pass arguments to functions. Positional arguments map directly to parameters in order from left to right. Keyword arguments map arguments explicitly by parameter name (`func(width=10, height=20)`), allowing you to pass them in any order.

Default parameter values let callers omit non-essential arguments: `def connect(host, port=5432):`. If the caller omits `port`, Python defaults it to `5432`.

The parameter order in a function definition must always follow a strict hierarchy: positional parameters first, followed by default parameters, then `*args`, followed by keyword-only parameters, and finally `**kwargs`.

## Packing & Unpacking with * and **

The single asterisk `*args` syntax collects an arbitrary number of extra positional arguments into an immutable tuple. This is useful for variadic functions like `math.prod(*numbers)` or custom wrappers.

The double asterisk `**kwargs` syntax collects an arbitrary number of extra keyword arguments into a standard Python dictionary. This is common in configuration APIs, decorators, and subclass method extensions.

Unpacking works in reverse when calling functions: prefixing an iterable with `*` expands elements into separate positional arguments (`func(*my_list)`). Prefixing a dictionary with `**` expands key-value pairs into named keyword arguments (`func(**my_dict)`).

## Keyword-Only Parameters and Safe Signatures

To force callers to pass arguments explicitly by name rather than position, place a bare asterisk `*` in the parameter list: `def export_csv(filename, *, delimiter=',', quotechar='"'):`.

Any parameter declared after the bare asterisk must be supplied as a keyword argument (e.g. `export_csv('data.csv', delimiter=';')`). Attempting to pass `export_csv('data.csv', ';')` raises a `TypeError`.

Similarly, Python 3.8 introduced positional-only parameters marked with `/`: parameters before `/` cannot be called via keyword name.

## Common mistake: The Infamous Mutable Default Argument Trap

Never use a mutable data structure (such as a list `[]`, dictionary `{}`, or set) as a default parameter value: `def append_to(item, target=[]): target.append(item); return target`.

In Python, default parameter values are evaluated exactly once when the function definition is executed at module load time, not every time the function is called.

As a result, `target` points to the exact same list instance in heap memory across every invocation. Calling `append_to('a')` followed by `append_to('b')` returns `['a', 'b']`, mutating shared state and causing bizarre bugs.

The Pythonic fix: always set the default value to `None`, and initialize the mutable object inside the function body using a guard: `if target is None: target = []`.

## Tip: Explicit is Better Than Implicit

Use keyword-only arguments for boolean flags and configuration options. Writing `get_records(limit=100, cache=False)` is immediately self-documenting for teammates reading your code, whereas `get_records(100, False)` leaves callers guessing what `False` controls.

## Try it: The Argument Distributor & Mutable Default Trap

Explore how Python routes arguments into *args tuples and **kwargs dictionaries. Switch to the mutable default trap to witness why default list arguments accumulate state across invocations.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/python/arguments-kwargs

## Check yourself

### Question 1

What is the result of running `f(1)` twice on the function `def f(val, items=[]): items.append(val); return items`?

- A. [1] on the first call, and [1, 1] on the second call
- B. [1] on both calls, because items is reinitialized to [] on each call
- C. TypeError: mutable defaults are prohibited by Python syntax
- D. None, because the function does not assign to a global variable

Correct answer: A

Default parameter values are evaluated once when the function is defined. Subsequent calls that omit the parameter share and mutate the same list object.

- Why not B: Python evaluates default argument expressions only once at function definition time.
- Why not C: Python permits mutable defaults syntactically, but it is considered an anti-pattern.
- Why not D: The function returns items, which points to the mutated shared default list.

### Question 2

What data types do `*args` and `**kwargs` receive inside the function body?

- A. *args receives a tuple, and **kwargs receives a dictionary
- B. *args receives a list, and **kwargs receives a dictionary
- C. *args receives a generator, and **kwargs receives a tuple of key-value pairs
- D. *args receives a set, and **kwargs receives an OrderedDict

Correct answer: A

Python packs unmatched positional arguments into a tuple named args, and unmatched keyword arguments into a dictionary named kwargs.

- Why not B: *args is packaged as an immutable tuple, not a mutable list.
- Why not C: *args is a concrete tuple and **kwargs is a concrete dictionary.
- Why not D: Python constructs a tuple for *args and a standard dict for **kwargs.

### Question 3

In the signature `def query(table, *, limit=100, timeout=30):`, how must `limit` and `timeout` be supplied by callers?

- A. They must be supplied as keyword arguments (e.g. limit=50)
- B. They can be supplied as positional arguments or keyword arguments
- C. They must be packed inside a single dictionary argument
- D. They can only be passed if **kwargs is also defined in the signature

Correct answer: A

A bare * in the parameter list marks all following parameters as keyword-only. Callers must specify their names when providing arguments.

- Why not B: The bare asterisk denotes that following parameters are keyword-only.
- Why not C: They are passed as standard keyword arguments (e.g. query('users', limit=50)).
- Why not D: Keyword-only parameters function independently of **kwargs.

## Remember this

- *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dictionary.
- Default parameter values are evaluated once at function definition time, making mutable defaults like [] dangerous.
- Always use target=None and initialize if target is None: target = [] for mutable optional arguments.
- A bare asterisk (*) in a function signature enforces that subsequent parameters must be passed by keyword name.
