Functions
Function Arguments
Complete lesson for Function Arguments using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Function Arguments
Section: Functions. Python function arguments — positional, keyword, defaults, *args, **kwargs, and packing rules.
Positional and keyword arguments
- Positional args match left-to-right. Keyword args use
name=valueand can reorder freely among themselves. - You may mix them, but positional must come before keyword in the call.
- Once you use a keyword for a parameter, later args must be keywords too.
def intro(name, city, role):
return f"{name} from {city} ({role})"
print(intro("Ada", "Pune", "dev"))
print(intro("Bob", role="qa", city="Delhi")) Default parameter values
- Defaults must follow non-default parameters:
def f(a, b=1). - Callers can omit defaults; explicit values override them.
- Defaults are great for optional flags and common settings.
def connect(host, port=5432, ssl=True):
return {"host": host, "port": port, "ssl": ssl}
print(connect("localhost"))
print(connect("db.local", 3306, False))
print(connect("db.local", ssl=False)) Mutable default anti-pattern
- Never use a mutable default like
def f(xs=[])— the same list is reused across calls. - Idiom:
def f(xs=None):thenif xs is None: xs = []. - This is one of the most common Python interview gotchas.
def bad_add(item, bucket=[]):
bucket.append(item)
return bucket
def good_add(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(bad_add(1), bad_add(2))
print(good_add(1), good_add(2)) *args — variable positional
*argscollects extra positional arguments into a tuple.- Useful for aggregators (
sum_all,print_all) and wrappers. - The name
argsis convention; the*is what matters.
def total(*nums):
return sum(nums)
def show(label, *values):
print(label, values)
print(total(1, 2, 3, 4))
show("nums", 10, 20, 30) **kwargs — variable keywords
**kwargscollects extra keyword arguments into a dict.- Common in constructors, config builders, and decorator wrappers.
- Do not pass the same key twice in one call.
def build_profile(name, **fields):
profile = {"name": name}
profile.update(fields)
return profile
print(build_profile("Ada", city="Pune", level=5)) Unpacking lists and dicts into calls
fn(*sequence)unpacks positionals;fn(**mapping)unpacks keywords.- Keys in the mapping must match parameter names (or be absorbed by
**kwargs). - Handy when arguments already live in a list/dict.
def volume(l, w, h):
return l * w * h
dims = [2, 3, 4]
opts = {"l": 2, "w": 3, "h": 5}
print(volume(*dims))
print(volume(**opts)) Keyword-only arguments
- Parameters after a bare
*must be passed by keyword. - Improves readability for boolean flags:
sort(data, *, reverse=False). - Callers cannot accidentally pass them positionally.
def send(email, *, urgent=False, retries=3):
return (email, urgent, retries)
print(send("a@b.com"))
print(send("a@b.com", urgent=True, retries=1)) Positional-only arguments (3.8+)
- Parameters before
/must be positional-only — cannot be passed by name. - Used in many builtins (
len(obj), notlen(obj=...)). - Helps APIs rename parameters later without breaking keyword callers.
def dist(x, y, /):
return (x * x + y * y) ** 0.5
print(dist(3, 4))
# dist(x=3, y=4) would raise TypeError Advanced — Function Arguments
Full signature order
- Order: positional-only, positional-or-keyword,
*args/ bare*, keyword-only,**kwargs. - Example:
def f(a, b=1, /, c=2, *args, d, e=3, **kwargs). - Keeping signatures simple usually beats using every feature at once.
def demo(a, b=0, /, c=1, *args, d, e=2, **kwargs):
return {
"a": a, "b": b, "c": c, "args": args,
"d": d, "e": e, "kwargs": kwargs,
}
print(demo(10, 20, 30, 40, 50, d=99, extra=True)) Defaults are evaluated once
- Default expressions run at **definition** time, not each call.
- That is why mutable defaults share state; also why
time.timeas default freezes one timestamp. - Use
Nonesentinels for “compute fresh each call”.
from datetime import datetime
def stamp(ts=datetime.now()):
return ts
def stamp_ok(ts=None):
if ts is None:
ts = datetime.now()
return ts
a = stamp()
b = stamp()
print(a is b)
print(stamp_ok() != stamp() or True) Forwarding arguments in wrappers
- Decorators and proxies often use
def wrapper(*args, **kwargs)thenreturn fn(*args, **kwargs). - Preserves flexibility for any signature of the wrapped callable.
functools.wrapscopies metadata when writing real decorators.
from functools import wraps
def traced(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
result = fn(*args, **kwargs)
print(fn.__name__, args, kwargs, "->", result)
return result
return wrapper
@traced
def add(a, b):
return a + b
add(2, 3)
add(a=5, b=7) Keyword argument clashes
- You cannot pass a positional and keyword for the same parameter.
- When unpacking
**dict, keys must be strings and valid identifiers for binding. - Overlapping keys between explicit kwargs and
**mappingraise TypeError.
def f(a, b):
return a + b
print(f(1, b=2))
try:
f(1, 2, b=3)
except TypeError as err:
print("error:", err) Tricky Interview Points
Q1) What are *args and **kwargs?
Answer *args collects extra positional args into a tuple; **kwargs collects extra keyword args into a dict.
Q2) Why is a mutable default argument dangerous?
Answer The default object is created once at function definition and shared across calls, so mutations persist unexpectedly.
Q3) What is a keyword-only argument?
Answer A parameter after * in the signature that must be supplied with its name, not positionally.
Q4) What does / mean in a function signature?
Answer Parameters before / are positional-only (Python 3.8+).
Q5) Can defaults appear before non-default parameters?
Answer No. Non-default parameters must come first (aside from advanced keyword-only layouts).
Q6) How do you unpack a list into a call?
Answer Use fn(*my_list) for positionals and fn(**my_dict) for keywords.
Q7) When are default values evaluated?
Answer At function definition time, once — not on every call.
Q8) Is the name args/kwargs mandatory?
Answer No. Only the * / ** syntax matters; args and kwargs are conventions.
Q9) What happens if you pass an unexpected keyword without **kwargs?
Answer Python raises TypeError: got an unexpected keyword argument.
Q10) How do wrappers forward any arguments?
Answer Define wrapper(*args, **kwargs) and call fn(*args, **kwargs) inside.
Q11) Positional after keyword in a call — allowed?
Answer No. In a call, keyword arguments cannot be followed by positional arguments.
Simple Programs
Logger with *args formatting
def log(level, *parts):
print(f"[{level}]", " ".join(str(p) for p in parts))
log("INFO", "server", "started", "on", 8080)
log("ERROR", "disk", "full") Config builder with **kwargs
def make_config(app, **opts):
cfg = {"app": app, "debug": False, "workers": 1}
cfg.update(opts)
return cfg
print(make_config("shop", debug=True, workers=4)) Safe append with None default
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item("a"))
print(add_item("b")) Keyword-only sort helper
def take_top(values, *, n=3, reverse=True):
return sorted(values, reverse=reverse)[:n]
print(take_top([5, 1, 9, 3, 7], n=2)) Unpacking into a formatted call
def paint(color, layers, finish):
return f"{layers}x {color} ({finish})"
args = ["blue", 2]
kw = {"finish": "matte"}
print(paint(*args, **kw)) Problem Solving Tricks
- Use keyword-only flags for booleans so calls read clearly at the site.
- Default to
Nonefor mutable optional containers. - When wrapping APIs, prefer
*args, **kwargsforwarding over hardcoding params. inspect.signature(fn)helps debug complex call signatures.- Avoid
**dictwith non-identifier keys when binding to parameters. - Put rarely changed options after
*so callers name them. - Keep
*argssmall — large anonymous positional lists hurt readability. - Document keyword-only params explicitly in the docstring.
- For public libraries, positional-only can protect against keyword coupling.
Practice Programs List
- Rewrite a 4-parameter function so the last two are keyword-only.
- Demonstrate the mutable default bug, then fix it with None.
- Write
mean(*nums)that errors on zero arguments. - Build
html_tag(name, **attrs)returning a fake opening tag string. - Call a function using both
*listand**dictunpacking together. - Create a decorator that logs kwargs keys before calling the function.
- Experiment with
/and show that keyword calls fail for positional-only params. - Write a merge function
merge(a, b, /, *, overwrite=True). - Compare readability of
fn(True, False)vsfn(*, verbose=True, dry_run=False). - Implement
retry(fn, *, times=3)that calls fn until success or times exhausted. - Use
inspect.signatureto print parameter kinds for a complex def.