Sub topic 5
Defaults are evaluated once, at definition time
This chapter assumes you can define and call functions, know the basic built-in types (numbers, strings, lists, dicts, None), and can read a simple traceback. You should also know that a parameter can have a default value, which the caller may omit.
When the default expression runs
A function definition is a statement. When Python executes def, it creates a function object and evaluates every default expression at that moment. The results are stored on the function object. Each later call that omits the argument reuses the stored value. Python does not run the expression again.
def make_default():
print("default evaluated")
return 1
def f(x=make_default()): # prints "default evaluated" once, here
return x
f()
f() # prints nothing moreThe message appears when the def line runs, before f is ever called. The two calls to f() only read the value that was saved.
Why this usually goes unnoticed
For an immutable value such as a number, a string, a tuple, or None, reuse is harmless. You cannot change the object in place, so every call sees the same unchanging value. Rebinding a local name inside the function replaces the local name only. It never alters the stored default.
The effect matters when the default is a mutable object, such as a list, dict, or set. Every call that uses the default shares that single object, so a change made in one call is visible in the next. The next chapter covers that bug in detail.
Defaults that look dynamic but are not
A common mistake is to expect a default to reflect the state at call time.
import time
def stamp(when=time.time()):
return when
first = stamp()
time.sleep(1)
second = stamp()
print(first == second) # Truetime.time() ran once, when def executed. Both calls return that same moment. The same problem affects defaults such as datetime.now() and random.random(). If you want a fresh value on every call, compute it inside the function body.
Seeing the stored defaults
The function object keeps its defaults in attributes. __defaults__ holds a tuple of defaults for ordinary parameters. __kwdefaults__ holds a dict for keyword-only parameters.
import inspect
def f(a, b=2, *, c=3):
pass
print(inspect.signature(f)) # (a, b=2, *, c=3)
print(f.__defaults__) # (2,)
print(f.__kwdefaults__) # {'c': 3}These attributes show that the defaults belong to the function object, not to any single call.
Common errors
- Calling a function in the default. Writing
x=compute()runscomputeonce at definition time. If you want it run on each call, use a sentinel and call it in the body. - Expecting a later change to a global to affect the default. If
LIMIT = 10whendefruns, the default stays 10, even if you setLIMIT = 20afterward. - Referring to an earlier parameter.
def f(a, b=a)raisesNameErrorwhendefruns, becauseais not defined at that point.
LIMIT = 10
def check(value, limit=LIMIT):
return value <= limit
LIMIT = 20
print(check(15)) # False, because the default is still 10Exercise
A module contains def log(message, when=datetime.now()): .... Every log line shows the same timestamp. Why does this happen, and how would you change the function so each call gets its own timestamp?
Show answer
datetime.now() runs once, when the def statement executes, and the resulting value is stored as the default. Every call that omits when reuses that stored timestamp. Change the default to None and compute the time in the body: def log(message, when=None): if when is None: when = datetime.now().
Exercise
What do f.__defaults__ and f.__kwdefaults__ return for def f(a, b=2, c=5, *, d=7): pass?
Show answer
f.__defaults__ is (2, 5), the defaults of the ordinary parameters b and c. f.__kwdefaults__ is {'d': 7}, the default of the keyword-only parameter d.