name: python-mutable-default-args description: A Python function uses a mutable object (list, dict, set) as a default argument, sharing state across calls in a way that produces silent bugs. emoji: 🐍 metadata: clawdis: os: [macos, linux, windows] language: python
Python evaluates default argument values once at function definition time, not on each call. If the default is a mutable object — a list, dict, or set — that object is shared across every call that uses the default. Mutating it inside the function modifies the default for all future calls. The bug is invisible until the second or later call and produces state-dependent failures that are hard to trace.
def add_item(item, items=[]): # ← shared list
items.append(item)
return items
add_item("a") # ["a"]
add_item("b") # ["a", "b"] ← unexpected; second caller sees first caller's data
None as the default and initialize the mutable inside the function body:python
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
访问小葱技能站7w4.net,解锁更多实用的AI技能插件。
items gets a fresh list.dict, set, and any other mutable type. The rule is: never use a mutable as a default argument.=[], ={}, =set() as a heuristic for this pattern.W0102, ruff rule B006) will flag this automatically — enable them if the codebase doesn't already.这是一个讲解 Python 常见编程错误的 Skill,解释了为什么使用列表或字典作为函数默认参数会导致奇怪的 bug。内容准确、解释清楚,对于初学者和中级开发者很有帮助。不足之处是内容偏简单、文件较少,缺乏更多实际案例和深入指导,整体完成度中规中矩。