Python Mutable Default Args

👤 mvogt99 📦 v1.0.0 ⭐ 4.4 ⬇️ 597 下載
💻 開發程式設計 免費

📖 技能介紹


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

    小蔥技能有更好的技能skills外掛。

  • Linters (pylint rule W0102, ruff rule B006) will flag this automatically — enable them if the codebase doesn't already.

🤖 AI 評測

這是一個講解 Python 常見程式設計錯誤的 Skill,解釋了為什麼使用列表或字典作為函式預設引數會導致奇怪的 bug。內容準確、解釋清楚,對於初學者和中級開發者很有幫助。不足之處是內容偏簡單、檔案較少,缺乏更多實際案例和深入指導,整體完成度中規中矩。

📊 多維度評分

適應性3.8
規範性4.5
有效性4.6
可靠性4.2
可信度4.3

📁 包含檔案 (2 個)

📄 SKILL.md 2 KB
📄 _meta.json 146 B