All articles
PythonGotchasDebugging

Python Mutable Defaults and Late-Binding Closures: Two Bugs That Pass Code Review

Why def f(x=[]) shares one list and lambdas in loops all see the last value, plus the sentinel, factory and partial fixes and the Ruff rules that catch them.

Tushar Pachouri12 min read

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 def runs, not on every call. A default [], {}, set() or datetime.now() is shared by every call that does not pass that argument.
  • Fix it with a None default (or a private _MISSING = object() sentinel when None is meaningful), and with field(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 pass args= instead of using a lambda.
  • Turn on Ruff's B006, B008 and B023 rules so the linter catches these before a reviewer has to.

Bug 1: mutable default arguments

Here is the classic version:

Python
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"))
Text
['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.

FUNCTION OBJECT LISTS CALLS add_item built once, when def runs __defaults__[0] ['apple', 'banana', 'date'] one shared default list add_item("apple")add_item("banana")add_item("date")add_item("cherry", []) ['cherry'] the caller's own list
Every call that omits items appends to the one list stored on the function object.

You can see the stored defaults directly:

Python
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"))
Text
([],)
(['apple', 'banana'],)
True

Tip: When a function "remembers" things it shouldn't, print func.__defaults__ (positional defaults) and func.__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:

Python
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))
Text
{'red': 2, 'green': 1}
{'red': 2, 'green': 1, 'blue': 1}
True
False

In 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:

Python
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"])
Text
True
0:00:00

Two 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:

Python
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)
Text
['apple']
['banana']
['kiwi', 'mango']

The same pattern fixes the timestamp:

Python
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)))
Text
[2024-07-24T09:30:00] pinned

Warning: 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:

Python
def add_item(item, items=None):
    items = items or []
    items.append(item)
    return items


basket = []
add_item("apple", basket)
print(basket)
Text
[]

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:

Python
_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"))
Text
{'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:

Python
from dataclasses import dataclass

try:
    @dataclass
    class Cart:
        owner: str
        items: list = []
except ValueError as exc:
    print(f"ValueError: {exc}")
Text
ValueError: mutable default <class 'list'> for field items is not allowed: use default_factory

The fix is default_factory, which is called once per instance. It also solves the timestamp problem, which dataclasses do not detect for you:

Python
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)
Text
['book'] []
False

Note: 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:

Python
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:

Python
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)
Text
['book']
True

Bob never added anything, but his cart has a book. Create per-instance state in __init__:

Python
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)
Text
['book'] []

This confuses people because the same pattern seems to work for counters:

Python
class Counter:
    count = 0

    def bump(self):
        self.count += 1


a = Counter()
b = Counter()
a.bump()
print(a.count, b.count, Counter.count)
Text
1 0 0

self.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.

Mutating changes the shared object; rebinding creates a new attribute on one instance.

Bug 2: late-binding closures

Now the second family. What does this print?

Python
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
print(funcs[0].__code__.co_freevars)
Text
[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.

CREATED IN THE LOOP ONE VARIABLE AT CALL TIME funcs[0]funcs[1]funcs[2] lambda: ilambda: ilambda: i variable i holds 2 after the loop read when f() runs [2, 2, 2] expected [0, 1, 2] The loop has finished when the lambdas run, so all three see i = 2
All three lambdas refer to the same variable i, which is 2 by the time they run.

Callbacks built in a loop

You rarely write that exact list comprehension in real code. You write this:

Python
handlers = {}
for name in ["save", "load", "quit"]:
    handlers[name] = lambda: f"clicked {name}"

print(handlers["save"]())
print(handlers["load"]())
Text
clicked quit
clicked quit

GUI code is the textbook case. In Tkinter, every button below reports Quit when clicked:

Python
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:

Python
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)
Text
[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:

Python
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())
Text
job 2 -> 0
job 2 -> 10
job 2 -> 20

The 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:

Python
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs])
print(funcs[0](99))
Text
[0, 1, 2]
99

It 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_callback calls your function with the task as its first argument, so lambda i=i: ... receives the Task object as i. 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:

Python
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"]())
Text
clicked save
clicked load

It is the cleanest fix for the asyncio case, since partial puts bound arguments before the ones the caller passes:

Python
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())
Text
job 0 -> 0
job 1 -> 10
job 2 -> 20

A factory function

Each call to a function creates a new scope, so a closure made inside a factory captures that call's own name:

Python
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"]())
Text
clicked save
clicked load

This 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:

Python
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))
Text
[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:

RuleCatchesExample
B006Mutable data structure as an argument defaultdef f(x=[])
B008Function call in an argument defaultdef f(when=datetime.now())
B023Function defined in a loop that uses the loop variablelambda: i inside for i in ...

Enable the whole bugbear set in pyproject.toml:

TOML
[tool.ruff.lint]
extend-select = ["B"]

Or check just these rules on an existing codebase:

Terminal
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 trips B008. Instead of turning the rule off, tell Ruff those calls are safe with extend-immutable-calls under [tool.ruff.lint.flake8-bugbear].

TOML
[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.

Defaults are fixed at definition time; closure variables are read at call time.

Stuck on something like this?

I build and fix full-stack products for startups and indie founders. Tell me what's broken.

Get in touch