Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

python-gotchas

БесплатноБез исполняемых скриптовНе проверен

Complete Python gotchas reference. PROACTIVELY activate for: (1) Mutable default arguments, (2) Mutating lists while iterating, (3) is vs == comparison, (4)…

JosiahSiegelот JosiahSiegel★ 67 звёзд на GitHub

Об этом скилле

Quick Reference

Gotcha Problem Fix
Mutable default def f(x=[]) Use None, create in function
Iterate + mutate Skips items Iterate over copy items[:]
is vs == Identity vs value Use is only for None
Late binding lambda: i captures var lambda i=i: i
Float precision 0.1 + 0.2 != 0.3 math.isclose()
Dict mutation RuntimeError list(d.keys())
Class attribute Shared mutable Init in __init__
Falsy Values Examples
Boolean False
None None
Numbers 0, 0.0, 0j
Empty collections "", [], {}, set()
Scope Rule Order
LEGB Local → Enclosing → Global → Built-in
global Access module-level variable
nonlocal Access enclosing function variable

When to Use This Skill

Use for debugging and prevention:

  • Understanding why code behaves unexpectedly
  • Avoiding common Python pitfalls
  • Reviewing code for subtle bugs
  • Learning Python's evaluation rules
  • Fixing mutable default arguments

Related skills:

  • For fundamentals: see python-fundamentals-313
  • For testing: see python-testing
  • For type hints: see python-type-hints

Python Common Gotchas and Pitfalls

Overview

Python has several well-known pitfalls that trip up developers of all experience levels. Understanding these gotchas prevents subtle bugs and unexpected behavior.

1. Mutable Default Arguments

The Problem

# BAD: Mutable default argument
def add_item(item, items=[]):
    items.append(item)
    return items

# Unexpected behavior!
print(add_item("a"))  # ['a']
print(add_item("b"))  # ['a', 'b'] - NOT ['b']!
print(add_item("c"))  # ['a', 'b', 'c']

Why It Happens

Default arguments are evaluated once when the function is defined, not each time it's called. The same list object is reused across all calls.

The Fix

# GOOD: Use None as default
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

# Works correctly
print(add_item("a"))  # ['a']
print(add_item("b"))  # ['b']
print(add_item("c"))  # ['c']

Other Mutable Defaults

# BAD: All mutable types have this issue
def bad_dict(data={}): ...
def bad_set(data=set()): ...
def bad_class(config=SomeClass()): ...

# GOOD: Always use None
def good_dict(data=None):
    if data is None:
        data = {}
    return data

def good_set(data=None):
    if data is None:
        data = set()
    return data

2. Mutating Lists While Iterating

The Problem

# BAD: Modifying list during iteration
numbers = [1, 2, 3, 4, 5, 6]
for num in numbers:
    if num % 2 == 0:
        numbers.remove(num)

print(numbers)  # [1, 3, 5] - missed 4!

Why It Happens

The iterator uses indices internally. When you remove an item, all subsequent indices shift, causing items to be skipped.

The Fixes

# GOOD: Iterate over a copy
numbers = [1, 2, 3, 4, 5, 6]
for num in numbers[:]:  # Slice creates a copy
    if num % 2 == 0:
        numbers.remove(num)
print(numbers)  # [1, 3, 5]

# GOOD: Use list comprehension (preferred)
numbers = [1, 2, 3, 4, 5, 6]
numbers = [num for num in numbers if num % 2 != 0]
print(numbers)  # [1, 3, 5]

# GOOD: Use filter
numbers = [1, 2, 3, 4, 5, 6]
numbers = list(filter(lambda x: x % 2 != 0, numbers))
print(numbers)  # [1, 3, 5]

# GOOD: Iterate backwards (for in-place modification)
numbers = [1, 2, 3, 4, 5, 6]
for i in range(len(numbers) - 1, -1, -1):
    if numbers[i] % 2 == 0:
        del numbers[i]
print(numbers)  # [1, 3, 5]

3. is vs ==

The Problem

# Comparing values vs identity
a = [1, 2, 3]
b = [1, 2, 3]

print(a == b)  # True - same values
print(a is b)  # False - different objects

# Integer interning gotcha
x = 256
y = 256
print(x is y)  # True (integers -5 to 256 are interned)

x = 257
y = 257
print(x is y)  # False! (outside interning range)

The Rule

  • Use == to compare values
  • Use is only for identity (singletons like None, True, False)
# GOOD: Correct usage
if value is None:
    ...

if value == other_value:
    ...

# BAD: Don't use `is` for value comparison
if value is 0:  # Wrong!
    ...

4. Variable Scope (LEGB)

The Problem

# Closure gotcha
functions = []
for i in range(3):
    functions.append(lambda: i)

# All return the same value!
print([f() for f in functions])  # [2, 2, 2]

Why It Happens

The lambda captures the variable i, not its value. By the time lambdas are called, i is 2.

The Fixes

# GOOD: Capture value with default argument
functions = []
for i in range(3):
    functions.append(lambda i=i: i)  # Default arg captures value
print([f() for f in functions])  # [0, 1, 2]

# GOOD: Use functools.partial
from functools import partial

def return_value
Полный SKILL.md на GitHub

Установить python-gotchas в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл python-gotchas?

Complete Python gotchas reference. PROACTIVELY activate for: (1) Mutable default arguments, (2) Mutating lists while iterating, (3) is vs == comparison, (4) Late binding in closures, (5) Variable scope (LEGB), (6) Floating point precision, (7) Exception handling pitfalls, (8) Dict mutation during iteration, (9) Circular imports, (10) Class vs instance attributes. Provides: Problem explanations, code examples, fixes for each gotcha. Ensures bug-free Python code.

Как установить скилл python-gotchas?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл python-gotchas запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить python-gotchas с