Sub topic 2
Defaults, Mutable Arguments, and Keyword-Only Parameters
Assume you can define and call Python functions and read simple tracebacks. The key idea is that a function definition stores its default values before any call happens.
Defaults are evaluated once, at definition time
A default expression runs when Python executes the def statement, not each time the function is called.
def make_default():
print("creating default")
return 10
def score(value=make_default()):
return value
print(score())
print(score())Output:
creating default
10
10The message appears once. Both calls reuse the stored value 10.
The mutable default argument pitfall
Lists and dictionaries are mutable objects. If one is used as a default, the same object is reused across calls.
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("a"))
print(add_item("b"))Output:
['a']
['a', 'b']The second call sees the list changed by the first call. This often causes surprising state to leak between calls.
Fixing it with a `None` sentinel
None is a special value commonly used to mean “no value was supplied.” Create the mutable object inside the function instead.
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item("a"))
print(add_item("b"))Each call now receives a fresh list. A caller can still provide an existing list when shared state is intended.
Keyword-only parameters with `*`
A bare * ends positional parameters. Every parameter after it must be passed by keyword. This makes important options clearer at the call site.
def connect(host, port=5432, *, timeout=10, ssl=True):
return host, port, timeout, ssl
print(connect("db.local", timeout=5))timeout and ssl cannot be supplied positionally. This call is invalid:
# connect("db.local", 5432, 5)Python raises a TypeError because timeout is keyword-only.
Exercise
Why does def f(value=[]): risk sharing data between calls?
Show answer
The list is created once when the definition runs, then reused whenever a call omits value. Use None and create a new list inside the function.