Some Python bugs look completely fine in a diff. A function with a default list, a lambda built inside a loop, a class with items = [] at the top: all three read naturally, pass tests that only call things once, and then misbehave in production when state starts leaking between calls. This post walks through both families of bug, shows exactly what Python does, and gives fixes you can paste in today.
TL;DR
- Default argument values are evaluated once, when the
defruns, not on every call. A default[],{},set()ordatetime.now()is shared by every call that does not pass that argument. - Fix it with a
Nonedefault (or a private_MISSING = object()sentinel whenNoneis meaningful), and withfield(default_factory=...)in dataclasses. - Closures look up variables when they run, not when they are created. Every lambda made in a loop sees the loop variable's final value.
- Bind the value at creation time:
lambda i=i: ...,functools.partial, a small factory function, or passargs=instead of using a lambda. - Turn on Ruff's
B006,B008andB023rules so the linter catches these before a reviewer has to.
Bug 1: mutable default arguments
Here is the classic version:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("apple"))
print(add_item("banana"))
print(add_item("cherry", []))
print(add_item("date"))['apple']
['apple', 'banana']
['cherry']
['apple', 'banana', 'date']The second call returns ['apple', 'banana'], not ['banana']. The call that passes its own list behaves, and then the next call without one picks up right where the shared list left off.
Why it happens
def is an executable statement. When Python runs it, it evaluates every default expression once and stores the results on the function object. Each call that omits the argument gets that same object, not a fresh copy. With an immutable value like 0 or "guest" you never notice. With a list, every append mutates the one stored default.
You can see the stored defaults directly:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item.__defaults__)
add_item("apple")
add_item("banana")
print(add_item.__defaults__)
print(add_item.__defaults__[0] is add_item("cherry"))([],)
(['apple', 'banana'],)
TrueTip: When a function "remembers" things it shouldn't, print
func.__defaults__(positional defaults) andfunc.__kwdefaults__(keyword-only defaults). If a default has grown, you have found your bug.
Dicts and sets do the same thing
Any mutable default behaves this way. Caches and "seen" sets are where it tends to show up, because the bug briefly looks like a feature:
def count_words(text, counts={}):
for word in text.split():
counts[word] = counts.get(word, 0) + 1
return counts
def is_new(user_id, seen=set()):
if user_id in seen:
return False
seen.add(user_id)
return True
print(count_words("red green red"))
print(count_words("blue"))
print(is_new(42))
print(is_new(42)){'red': 2, 'green': 1}
{'red': 2, 'green': 1, 'blue': 1}
True
FalseIn a long-running web worker, is_new quietly turns into a process-wide memory leak that also gives different answers depending on which worker handles the request.
Function calls in defaults: datetime.now()
The same rule applies to any expression, including function calls. This one is especially sneaky because nothing is mutated:
import time
from datetime import datetime
def make_event(name, created_at=datetime.now()):
return {"name": name, "created_at": created_at}
signup = make_event("signup")
time.sleep(2)
login = make_event("login")
print(signup["created_at"] == login["created_at"])
print(login["created_at"] - signup["created_at"])True
0:00:00Two seconds passed between the calls, but both events have the timestamp of when the module was imported. The same thing happens with uuid.uuid4(), time.time(), random.random(), or load_config() in a default.
Fixing mutable defaults
Use None as the default
The standard fix is to default to None and build the real value inside the function body, which runs on every call:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item("apple"))
print(add_item("banana"))
mine = ["kiwi"]
add_item("mango", mine)
print(mine)['apple']
['banana']
['kiwi', 'mango']The same pattern fixes the timestamp:
from datetime import datetime
def log(msg, when=None):
if when is None:
when = datetime.now()
return f"[{when.isoformat(timespec='seconds')}] {msg}"
print(log("pinned", when=datetime(2024, 7, 24, 9, 30)))[2024-07-24T09:30:00] pinnedWarning: Do not shorten the check to
items = items or []. An empty list is falsy, so a caller who passes their own empty list gets it silently swapped for a new one, and their list never changes.
Here is that trap in action:
def add_item(item, items=None):
items = items or []
items.append(item)
return items
basket = []
add_item("apple", basket)
print(basket)[]Always compare with is None.
Use a private sentinel when None is a real value
Sometimes None means something, for example "clear this field" in a PATCH-style update. Then you need a way to tell "argument not passed" apart from "argument passed as None". Create a unique object that nobody else can pass by accident:
_MISSING = object()
def update_profile(profile, *, nickname=_MISSING):
updated = dict(profile)
if nickname is not _MISSING:
updated["nickname"] = nickname
return updated
profile = {"name": "Ada", "nickname": "countess"}
print(update_profile(profile))
print(update_profile(profile, nickname=None))
print(update_profile(profile, nickname="ada")){'name': 'Ada', 'nickname': 'countess'}
{'name': 'Ada', 'nickname': None}
{'name': 'Ada', 'nickname': 'ada'}Because object() creates a brand-new object, the is check can only match if the caller left the argument out.
Dataclasses: field(default_factory=...)
Dataclasses refuse the obvious mistake outright:
from dataclasses import dataclass
try:
@dataclass
class Cart:
owner: str
items: list = []
except ValueError as exc:
print(f"ValueError: {exc}")ValueError: mutable default <class 'list'> for field items is not allowed: use default_factoryThe fix is default_factory, which is called once per instance. It also solves the timestamp problem, which dataclasses do not detect for you:
from dataclasses import dataclass, field
from datetime import datetime
@dataclass
class Cart:
owner: str
items: list[str] = field(default_factory=list)
created_at: datetime = field(default_factory=datetime.now)
a = Cart("alice")
b = Cart("bob")
a.items.append("book")
print(a.items, b.items)
print(a.items is b.items)['book'] []
FalseNote: Pass the function itself (
datetime.now), not the result of calling it (datetime.now()). The second form is the same once-at-definition bug in a new place.
Pydantic handles list defaults for you
Pydantic models are a pleasant exception. Writing items: list[str] = [] on a BaseModel is safe, because Pydantic copies a mutable default for each new instance instead of sharing it. Values that must be computed fresh still need a factory:
from datetime import datetime
from pydantic import BaseModel, Field
class Cart(BaseModel):
owner: str
items: list[str] = []
created_at: datetime = Field(default_factory=datetime.now)
a = Cart(owner="alice")
b = Cart(owner="bob")
a.items.append("book")
print(a.items, b.items)b.items stays empty here. Just remember this guarantee belongs to Pydantic models only. Plain functions and plain classes in the same codebase still need the None pattern.
Shared mutable class attributes
A close cousin of the default-argument bug lives on classes. Anything assigned in the class body is created once and shared by every instance:
class Cart:
items = []
def add(self, item):
self.items.append(item)
alice = Cart()
bob = Cart()
alice.add("book")
print(bob.items)
print(alice.items is bob.items is Cart.items)['book']
TrueBob never added anything, but his cart has a book. Create per-instance state in __init__:
class Cart:
def __init__(self):
self.items = []
def add(self, item):
self.items.append(item)
alice = Cart()
bob = Cart()
alice.add("book")
print(alice.items, bob.items)['book'] []This confuses people because the same pattern seems to work for counters:
class Counter:
count = 0
def bump(self):
self.count += 1
a = Counter()
b = Counter()
a.bump()
print(a.count, b.count, Counter.count)1 0 0self.count += 1 rebinds the name, which creates a new instance attribute on a. self.items.append(...) mutates the shared object and never rebinds anything. That difference between rebinding and mutating is the root of every bug in this post.
Bug 2: late-binding closures
Now the second family. What does this print?
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
print(funcs[0].__code__.co_freevars)[2, 2, 2]
('i',)Most people expect [0, 1, 2]. The lambda does not store the value of i. It stores a reference to the variable i (that is what co_freevars is showing) and looks it up when it is called. By then the loop has finished and i is 2.
Callbacks built in a loop
You rarely write that exact list comprehension in real code. You write this:
handlers = {}
for name in ["save", "load", "quit"]:
handlers[name] = lambda: f"clicked {name}"
print(handlers["save"]())
print(handlers["load"]())clicked quit
clicked quitGUI code is the textbook case. In Tkinter, every button below reports Quit when clicked:
import tkinter as tk
def on_click(name):
print(f"clicked {name}")
root = tk.Tk()
for name in ["Save", "Load", "Quit"]:
tk.Button(root, text=name, command=lambda: on_click(name)).pack()
root.mainloop()Threads: a race on top of a bug
Threads make it worse, because the result depends on timing:
import threading
results = []
def work(n):
results.append(n)
threads = [threading.Thread(target=lambda: work(i)) for i in range(3)]
for t in threads:
t.start()
for t in threads:
t.join()
print(results)[2, 2, 2]Here every thread starts after the loop finished, so the output is consistently wrong. If you call t.start() inside the loop instead, some threads may run before i changes and some after, so you get a different wrong answer on different runs. That kind of bug survives a quick local test and then shows up under load.
asyncio done-callbacks
With asyncio, asyncio.create_task(fetch(i)) is fine, because fetch(i) is called immediately and receives the current value. The lambda you attach as a callback is not:
import asyncio
async def fetch(n):
await asyncio.sleep(0.01 * n)
return n * 10
async def main():
tasks = []
for i in range(3):
task = asyncio.create_task(fetch(i))
task.add_done_callback(lambda t: print(f"job {i} -> {t.result()}"))
tasks.append(task)
await asyncio.gather(*tasks)
asyncio.run(main())job 2 -> 0
job 2 -> 10
job 2 -> 20The results are right but every log line blames job 2, which is exactly the kind of thing that wastes an afternoon of debugging.
Fixing late binding
All the fixes do the same thing: capture the current value when the function is created.
Default-argument capture
Defaults are evaluated at definition time, which is the bug from part one, used on purpose:
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs])
print(funcs[0](99))[0, 1, 2]
99It is short and idiomatic, and it fixes the Tkinter example (command=lambda name=name: on_click(name)). The second line shows the cost: the captured value is now a public parameter that a caller can override.
Warning: That override can happen without anyone meaning to.
add_done_callbackcalls your function with the task as its first argument, solambda i=i: ...receives theTaskobject asi. If the callback is passed arguments, put them first:lambda t, i=i: print(f"job {i} -> {t.result()}").
functools.partial
partial binds arguments right away and makes the intent explicit:
from functools import partial
def on_click(name):
return f"clicked {name}"
handlers = {name: partial(on_click, name) for name in ["save", "load", "quit"]}
print(handlers["save"]())
print(handlers["load"]())clicked save
clicked loadIt is the cleanest fix for the asyncio case, since partial puts bound arguments before the ones the caller passes:
import asyncio
from functools import partial
async def fetch(n):
await asyncio.sleep(0.01 * n)
return n * 10
def report(job_id, task):
print(f"job {job_id} -> {task.result()}")
async def main():
tasks = []
for i in range(3):
task = asyncio.create_task(fetch(i))
task.add_done_callback(partial(report, i))
tasks.append(task)
await asyncio.gather(*tasks)
asyncio.run(main())job 0 -> 0
job 1 -> 10
job 2 -> 20A factory function
Each call to a function creates a new scope, so a closure made inside a factory captures that call's own name:
def make_handler(name):
def handler():
return f"clicked {name}"
return handler
handlers = {name: make_handler(name) for name in ["save", "load", "quit"]}
print(handlers["save"]())
print(handlers["load"]())clicked save
clicked loadThis is the most readable option when the callback is more than one line.
Skip the lambda entirely
For threads, the best fix is to not need a closure at all. Thread takes the arguments directly and evaluates them on the spot:
import threading
results = []
def work(n):
results.append(n)
threads = [threading.Thread(target=work, args=(i,)) for i in range(3)]
for t in threads:
t.start()
for t in threads:
t.join()
print(sorted(results))[0, 1, 2]The same goes for executor.submit(work, i) and loop.call_soon(callback, i). If an API takes *args, use them.
Let the linter catch it
Both bug families are mechanical enough for static analysis to flag reliably. The flake8-bugbear rules, which Ruff also implements, cover them:
| Rule | Catches | Example |
|---|---|---|
B006 | Mutable data structure as an argument default | def f(x=[]) |
B008 | Function call in an argument default | def f(when=datetime.now()) |
B023 | Function defined in a loop that uses the loop variable | lambda: i inside for i in ... |
Enable the whole bugbear set in pyproject.toml:
[tool.ruff.lint]
extend-select = ["B"]Or check just these rules on an existing codebase:
ruff check --select B006,B008,B023 .If you use flake8, pip install flake8-bugbear adds the same codes. Pylint reports the mutable default case as W0102 (dangerous-default-value).
Tip: Frameworks like FastAPI deliberately use calls such as
Depends(...)in defaults, which tripsB008. Instead of turning the rule off, tell Ruff those calls are safe withextend-immutable-callsunder[tool.ruff.lint.flake8-bugbear].
[tool.ruff.lint.flake8-bugbear]
extend-immutable-calls = ["fastapi.Depends", "fastapi.Query"]Ruff also has RUF012, which flags mutable class attributes like items = [] that are not annotated as ClassVar. Turning it on catches the shared Cart case.
Wrapping up
Both bugs come from one question: when does Python evaluate this? Default values are evaluated once, when the function is defined. Variables in a closure are looked up later, when the function is called. Once that clicks, the fixes make sense. Defer the work to call time with None or default_factory, and pull the value forward to creation time with i=i, partial or a factory. Then add B006, B008 and B023 to your lint config so the next one never reaches code review.