← 返回
未分类 中文

Python Mutable Default Args

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.
Python 函数使用可变对象(列表、字典、集合)作为默认参数,导致调用间共享状态,产生静默 bug。
mvogt99 mvogt99 来源
未分类 clawhub v1.0.0 1 版本 100000 Key: 无需
★ 0
Stars
📥 308
下载
💾 0
安装
1
版本
#latest

概述

python-mutable-default-args

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.

Symptoms

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
  • A function that accumulates data into a list or dict default grows unboundedly across calls.
  • A function that should be stateless produces different results on the second call than the first.
  • Unit tests pass in isolation but fail when run together due to shared state from a prior test.
  • The bug disappears if the function is called with an explicit argument.

What to do

  • Use 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

```

  • This is the canonical Python idiom. Every call that omits items gets a fresh list.
  • Applies equally to dict, set, and any other mutable type. The rule is: never use a mutable as a default argument.
  • When reviewing code, scan every function signature for =[], ={}, =set() as a heuristic for this pattern.
  • Linters (pylint rule W0102, ruff rule B006) will flag this automatically — enable them if the codebase doesn't already.

版本历史

共 1 个版本

  • v1.0.0 当前
    2026-05-08 00:39 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

data-analysis

Analysis Missing Tradeoffs

mvogt99
分析仅呈现单一选项,未比较替代方案,也未说明所选方案的成本。
★ 0 📥 671
dev-programming

Mcporter

steipete
使用 mcporter CLI 直接列出、配置、认证及调用 MCP 服务器/工具(支持 HTTP 或 stdio),涵盖临时服务器、配置编辑及 CLI/类型生成功能。
★ 196 📥 67,901
dev-programming

Github

steipete
使用 `gh` CLI 与 GitHub 交互,通过 `gh issue`、`gh pr`、`gh run` 和 `gh api` 管理议题、PR、CI 运行及高级查询。
★ 681 📥 329,048