Sub topic 5
Defaults are evaluated once, at definition time
This chapter assumes you can write and call functions, know that def is a statement that runs, and can read a simple traceback. It also assumes you know how to give a parameter a default value. The rule here is when that default value gets computed. Many default-argument surprises follow from that one rule.
The rule
Python evaluates the expression after = in a parameter list once, when the def statement runs. The resulting object is stored on the function object. Every later call that omits the argument receives that same stored object.
def make_default():
print("default evaluated")
return 1
def f(x=make_default()): # prints "default evaluated" once, here
return x
f()
f() # prints nothing moreRunning this prints default evaluated exactly once, before either call to f. The calls f() and f() only read the stored value 1.
A common mental model is that the default is "re-run on every call", the way the body is. That model is wrong. The parameter list belongs to the def statement, and the body belongs to the call.
Where the stored defaults live
The function object keeps the defaults in two attributes. __defaults__ is a tuple for ordinary parameters, and __kwdefaults__ is a dict for keyword-only parameters. You can use these to confirm that a call receives the stored object itself, not a copy.
def f(x=[]):
return x
print(f() is f.__defaults__[0]) # True
print(f() is f()) # TrueBoth comparisons print True. Every call that omits x returns the one list sitting in f.__defaults__. The next chapter looks at why this matters for mutable objects such as lists. Here the point is only that the identity is shared.
Consequence 1: the default does not track the current time
An expression such as time.time() or datetime.now() is evaluated at definition time. The value is frozen at that moment.
import time
def log(message, when=time.time()):
return (message, when)
first = log("a")
time.sleep(0.01)
second = log("b")
print(first[1] == second[1]) # TrueBoth calls report the time at which def log ran, not the time of the call. The fix is to evaluate inside the body, using None as a marker for "not provided":
import time
def log(message, when=None):
if when is None:
when = time.time()
return (message, when)The same applies to random numbers (random.random()), unique IDs (uuid.uuid4()), and anything else that should differ per call.
Consequence 2: later changes to a name do not affect the default
The default captures a value, not a variable. If the expression is a bare name, Python looks the name up once, at definition time, and stores the object it finds.
limit = 10
def check(value, max_value=limit):
return value <= max_value
limit = 5
print(check(8)) # True (default is still 10)
print(check(8, limit)) # False (explicit argument is 5)Rebinding limit afterwards does nothing to the stored default. If you want a call to see the current value of a module-level setting, read it in the body instead of in the parameter list.
Consequence 3: a default cannot use earlier parameters
When Python evaluates the defaults, no call exists yet. The other parameters have no values at that point. A default expression can therefore only use names that already exist in the surrounding scope.
# def area(width, height=width): # NameError at definition time:
# return width * height # name 'width' is not definedNote that the error appears when the def runs, not when you call the function. (If a global named width happened to exist, the line would not fail. It would silently use that global, which is worse.) The standard way to default one parameter from another is the same marker pattern:
def area(width, height=None):
if height is None:
height = width
return width * height
print(area(3)) # 9
print(area(3, 4)) # 12Each execution of def creates a new default
The "once" in the rule means once per execution of the def statement, not once per program. If a def sits inside another function, a loop, or a conditional, each execution builds a new function object with freshly evaluated defaults.
def make_counter_log():
def record(entry, store=[]):
store.append(entry)
return store
return record
a = make_counter_log()
b = make_counter_log()
a("x")
a("y")
print(a("z")) # ['x', 'y', 'z']
print(b("q")) # ['q']The inner def record runs once for each call to make_counter_log, so a and b each get their own list. Calls to a still share a list with each other. The same holds for methods. Defaults in a method are evaluated when the class body runs, so all instances of the class share them.
A related idiom: capturing loop variables
Closures look up variables when they are called, which is later than you often expect. Defaults are evaluated at definition time, so you can use them to freeze a value on purpose.
late = [lambda: i for i in range(3)]
early = [lambda i=i: i for i in range(3)]
print([f() for f in late]) # [2, 2, 2]
print([f() for f in early]) # [0, 1, 2]In late, every lambda reads the variable i when called, after the loop has ended with i == 2. In early, i=i evaluates the loop's current i at the moment each lambda is defined and stores it as that lambda's default. This idiom is common in older code. Be aware that it adds a parameter, so a caller can override it by accident.
Immutable defaults are safe, and why
Defaults such as numbers, strings, None, True, and tuples of those cannot change in place. A function that "modifies" such a parameter only rebinds a local name to a new object and leaves the stored default alone.
def bump(n=0):
n += 1 # rebinds the local name n to a new int
return n
print(bump()) # 1
print(bump()) # 1
print(bump.__defaults__) # (0,)The stored default stays 0. With a list, items.append(...) mutates the stored object itself. The difference between rebinding a name and mutating an object is the whole mechanism behind the next chapter's bug.
Deliberate use of the one-time evaluation
Sometimes you want a value computed once, such as a cache shared by all calls or an expensive lookup table.
def fib(n, _cache={0: 0, 1: 1}):
if n not in _cache:
_cache[n] = fib(n - 1) + fib(n - 2)
return _cache[n]
print(fib(30)) # 832040This works because the dict is created once and persists. It is also hidden shared state that a caller can override, so many teams prefer functools.lru_cache or a module-level variable. If you use this trick, mark the parameter private with a leading underscore and add a comment saying it is intentional.
Quick reference
| Default expression | Evaluated | Safe to share across calls? |
|---|---|---|
| `0`, `"text"`, `None`, `True` | Once at `def` | Yes, immutable |
| `(1, 2)` | Once at `def` | Yes, immutable |
| `[]`, `{}`, `set()` | Once at `def` | No, mutable |
| `time.time()`, `uuid.uuid4()` | Once at `def` | Value is frozen, rarely what you want |
| A global name such as `limit` | Name looked up once at `def` | Later rebinding of the name is ignored |
Exercise
This function is meant to stamp each record with the time of the call. Why do all records get the same stamp, and how do you fix it? import datetime def make_record(text, created=datetime.datetime.now()): return {"text": text, "created": created}
Show answer
The expression datetime.datetime.now() is evaluated once, when the def statement runs, and the resulting datetime object is stored in makerecord.defaults. Every call that omits created reuses that stored value. Fix it with a None marker: def makerecord(text, created=None): if created is None: created = datetime.datetime.now(). Now the time is read inside the body on each call, and callers can still pass an explicit timestamp.
Exercise
What do the three print calls output, and why? scale = 2 def apply(x, factor=scale): return x * factor scale = 10 print(apply(5)) print(apply(5, scale)) print(apply._defaults_)
Show answer
They print 10, 50, and (2,). The default factor was bound to the object 2 when def ran. Rebinding scale to 10 afterwards does not change the stored default, so apply(5) returns 5 * 2 = 10. Passing scale explicitly supplies 10, so apply(5, scale) returns 50. The _defaults_ tuple still holds (2,).