Lesson · Functions
Parameters & Arguments
66 min readParameters & Arguments
Python has a rich parameter system: positional-only, positional-or-keyword, keyword-only, variadic positional, and variadic keyword parameters. Understanding binding rules makes function APIs predictable.
Learning goals
- Read a signature and label each parameter: positional-only, positional-or-keyword, keyword-only, or variadic.
- Predict how a call binds, including which defaults get used and what lands in
*argsand**kwargs. - Explain what the
/and*markers inconnect(host, /, port=443, *, timeout=5, **options)permit and forbid. - Choose safe defaults and explain why a mutable default is shared by every call.
- Collect extra arguments into a tuple or dictionary and expand a list or mapping back into a call.
Mental model
Binding is a matching process with a strict order: positional arguments fill parameters from left to right, keyword arguments fill by name, defaults cover whatever is still unfilled, and *args and **kwargs absorb the leftovers. Anything that fails to match, or that matches twice, is rejected before the first body statement runs, which is why malformed calls raise instead of half-working.
Binding matches arguments to parameters
positional fill left to right, keywords bind by name, the rest collect
Mental model
the same mechanism as a compact list
connect("example.com", timeout=2, retries=3)
↓ position: "example.com" fills host (the parameter before /)
↓ keyword: timeout=2 fills timeout, retries=3 lands in **options
port=443 the default fills what nothing else claimed
↓ all arguments matched, body starts
print(host, port, timeout, options) the local namespace is the match resultCore idea
A call is a binding problem and the signature holds the rules: positional arguments match by order, keyword arguments match by name, defaults cover omissions, and *args plus **kwargs collect what remains. Every interesting error in this lesson, a duplicate value for one parameter, a stray keyword, a value on the wrong side of / or *, is a failed match detected before the body runs.
Positional arguments
Positional arguments bind to parameters by order. They are concise for obvious required values but become hard to read when many same-typed options appear.
Keyword arguments
Keyword arguments bind by parameter name and make call intent explicit. They also allow callers to omit earlier defaulted parameters without relying on position.
Default arguments
Default expressions are evaluated once when the function definition executes. Use immutable defaults or a sentinel pattern when each call needs fresh mutable state.
Positional-only parameters
Parameters before / can only receive arguments by position. This can protect API flexibility by preventing callers from depending on internal parameter names.
Keyword-only parameters
Parameters after * must be supplied by name. Keyword-only parameters make calls self-documenting when several options have similar types or meanings.
\*args
*args collects extra positional arguments into a tuple. Prefer it when a function genuinely accepts a variable number of homogeneous positional values.
\*\*kwargs
**kwargs collects extra keyword arguments into a dictionary. Avoid using it as a substitute for a clear, documented public API unless forwarding or extensibility is intentional.
Argument unpacking
*iterable expands positional arguments and **mapping expands keyword arguments at a call site. The final call must still satisfy the target signature without duplicate bindings.
Parameter binding rules
Argument binding maps supplied positional and keyword arguments onto the function's parameter definitions before the body starts. Invalid calls fail before normal body execution.
Walkthrough
- In
connect(host, /, port=443, *, timeout=5, **options)the/makeshostpositional-only and the*makestimeoutkeyword-only;portsits between the markers and accepts either style. connect("example.com", timeout=2, retries=3)bindshost="example.com"by position, keepsport=443from the default, bindstimeout=2by name, and collects{"retries": 3}intooptions.collect(first, *items)bindsfirst=1and gathers(2, 3, 4)into the tupleitems, so the call returns(1, (2, 3, 4))andprintshows the nested tuple.- Predict before running: why
connect(host="example.com")is rejected even thoughhostlooks like an ordinary parameter name.
Experiments to try
- Call
connect("example.com"), thenconnect("example.com", 8443), thenconnect("example.com", port=8443), and compare the printedportin all three. - Pass
hostby keyword withconnect(host="example.com")and read theTypeError; quote the part of the message that says positional-only arguments cannot arrive by name. - Write
def enqueue(item, queue=[]): queue.append(item); return queue, call it twice without the second argument, and print the results to watch one shared list collect both items. - Unpack at the call site: set
parts = ["example.com", 8080]andopts = {"timeout": 1}, callconnect(*parts, **opts), then add"port"tooptsand watch the duplicate binding get rejected.
Playable lesson
Lab: Function argument binding lab
Let the learner build calls against signatures that use /, *, defaults, *args, and **kwargs. Show the resulting local parameter namespace.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Argument binding lab
add arguments, then read the bindingAdd an argument
The call
click a chip to remove it
TypeError: connect() missing 1 required positional argument: 'host'
Local namespace after binding
Badge colour shows how each name was filled: blue by position, violet by keyword, grey from the default, red when nothing filled it.
Predict first
For `connect("example.com", timeout=2, retries=3)`, what lands in `options`?
Predict first
Can the first argument arrive as `connect(host="example.com")`?
Predict first
`connect("example.com", 8443)` fills which parameter with 8443?
Common mistakes
- Using a mutable default such as
def enqueue(item, queue=[]): the list is built once when thedefstatement executes, so every call that omits the argument shares and grows that same list. - Mixing up the markers: parameters before
/reject keyword arguments and parameters after*reject positional ones, so the mismatch raisesTypeErrorduring binding, before any body line runs. - Passing one parameter twice, as in
connect("example.com", port=443, **{"port": 8080}): binding sees two values forportand rejects the call instead of letting the later one win. - Treating
**optionsas pre-existing state: it is a fresh dictionary assembled from the call's extra keywords, empty when none are supplied and linked to nothing outside the call.
Practice: Easy
- Call
connect("example.com"),connect("example.com", 8443), andconnect("example.com", port=8443); write down the printedport,timeout, andoptionsfor each call. - Try
connect(host="example.com")andconnect("example.com", timeout=2, host="other"); for eachTypeError, name the binding rule that rejected the call. - Predict the shape of
itemsincollect(1)andcollect(1, 2), then run both calls and compare the tuples with your prediction.
Practice: Medium
- Extend
connectwith a keyword-onlyverify=Falseparameter and call it once with and once withoutverify; note which value each call uses. - Write
def total(*prices, currency="USD"), calltotal(1.5, 2.5, currency="EUR"), and explain which marker makescurrencyreachable only by name. - Reproduce the shared-default trap with
def log(entry, entries=[]): entries.append(entry); return entries, call it twice omitting the second argument, then repair the signature withentries=Noneand a fresh list built inside the body.
Practice: Hard
- Design a
request(url, /, *, method="GET", headers=None, **params)signature: state the rule each marker enforces, then write three valid calls and three that fail for different reasons, quoting the rejection each time. - Build a binder test for
def binder(a, /, b=2, *, c=3, **rest): write five calls, predict each call's parameter values or its error before running, then check every prediction. - Build a forwarding wrapper
def traced(*args, **kwargs)that prints its arguments and delegates withconnect(*args, **kwargs); call it with("example.com",)and{"timeout": 2}and confirm the binding matches a direct call toconnect.
Lesson checklist
- I can label every parameter in a signature as positional-only, regular, keyword-only, or variadic.
- I can predict which arguments fill which parameters for a given call, defaults included.
- I can explain why a call that duplicates a binding fails before the body runs.
- I can replace a mutable default with
Noneand a fresh object created inside the function.
Remember
A call is a binding problem: the signature decides which parameters take arguments by position, which take them by name, which have defaults, and which collect the leftovers as `*args` and `**kwargs`. Read the `/` and `*` markers, treat default expressions as evaluated once at definition time, and most "why was this call rejected" questions answer themselves before the body ever runs.
Interview angles
What is the main purpose of **Positional arguments**?+
Positional arguments bind to parameters by order. They are concise for obvious required values but become hard to read when many same-typed options appear.
What should you pay attention to when using **Keyword arguments**?+
Keyword arguments bind by parameter name and make call intent explicit. They also allow callers to omit earlier defaulted parameters without relying on position.
How does **Default arguments** fit into this lesson?+
Default expressions are evaluated once when the function definition executes. Use immutable defaults or a sentinel pattern when each call needs fresh mutable state.
Why does a default like `queue=[]` surprise callers on the second call?+
The default expression is evaluated once, when the def statement executes, so every call that omits the argument shares one list object; an item appended in one call is still there in the next. Use None as the default and build a fresh list inside the function instead.