Learning navigation

Code with Animation

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.

Python7 min readConcept 10 of 24

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.

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.

Select Visualizer Mode:
# 1. Parameter signature:
def append_item(val, target=[]):
target.append(val)
return target
# Warning: target evaluated once!
# 2. Sequential calls: (1/3)
res = append_item("item_1")
# 3. Accumulated return value:
# res = ["item_1"]
MUTABLE DEFAULT TRAP (target=[])FUNCTION OBJECT @ 0x7fa0fn.__defaults__ slottarget default memory:List @ 0x90bc (MUTABLE HEAP BUFFER)HEAP STATE ACROSS 1 CALL:Shared List @ 0x90bc Accumulating State:Contents in target (len = 1):["item_1"]
★ Python Rule: Default parameter values are evaluated exactly once at module load time. If a default is mutable ([] or {}), all invocations mutate that shared instance. Always use None as default.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the result of running `f(1)` twice on the function `def f(val, items=[]): items.append(val); return items`?
  2. 2What data types do `*args` and `**kwargs` receive inside the function body?
  3. 3In the signature `def query(table, *, limit=100, timeout=30):`, how must `limit` and `timeout` be supplied by callers?

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.

Done with this concept?

Mark it complete to track your progress. No login needed.