关于 python-gotchas
面向 Python 开发者的常见陷阱参考技能,适用于调试、代码审查和预防细微错误,结合问题原因与修复方式说明语言行为。
主要功能
- 01解释可变默认参数问题及修复
- 02说明迭代时修改列表或字典的风险
- 03区分身份比较与值比较
- 04涵盖闭包绑定、作用域和浮点精度
- 05提醒异常处理、导入与类属性陷阱
适用场景
- 01排查 Python 代码中的意外行为
- 02审查代码以发现潜在错误
- 03学习 Python 求值和作用域规则
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ josiahsiegel/ claude-plugin-marketplace --skill python-gotchas安装后在 Claude Code 中输入/python-gotchas确认已加载。
详细介绍
快速参考
| 易踩的坑 | 问题 | 修复方法 |
|---|---|---|
| 可变默认值 | def f(x=[]) | 使用 None,并在函数中创建 |
| 遍历时修改 | 跳过条目 | 遍历副本 items[:] |
is 与 == | 身份与值 | 仅对 None 使用 is |
| 延迟绑定 | lambda: i 捕获变量 | lambda i=i: i |
| 浮点精度 | 0.1 + 0.2 != 0.3 | math.isclose() |
| 修改字典 | RuntimeError | list(d.keys()) |
| 类属性 | 可变对象会被共享 | 在 __init__ 中初始化 |
| 假值 | 示例 |
|---|---|
| 布尔值 | False |
| None | None |
| 数字 | 0、0.0、0j |
| 空集合 | ""、[]、{}、set() |
| 作用域规则 | 顺序 |
|---|---|
| LEGB | 局部 → 闭包 → 全局 → 内置 |
global | 访问模块级变量 |
nonlocal | 访问外层函数变量 |
何时使用此技能
用于调试和预防:
- 理解代码行为异常的原因
- 避免常见的 Python 陷阱
- 检查代码中难以察觉的错误
- 学习 Python 的求值规则
- 修复可变默认参数
相关技能:
- 基础知识:参见
python-fundamentals-313 - 测试:参见
python-testing - 类型提示:参见
python-type-hints
Python 常见陷阱与易错点
概述
Python 中有一些广为人知的陷阱,会让各种经验水平的开发者都感到棘手。了解这些易错点有助于避免隐蔽错误和意外行为。
1. 可变默认参数
问题
# 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']
原因
默认参数在函数定义时只求值一次,而不是每次调用时求值。所有调用都会重复使用同一个列表对象。
修复方法
# 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']
其他可变默认值
# 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. 遍历列表时修改列表
问题
# 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!
原因
迭代器内部使用索引。当你移除一项时,后续所有索引都会移动,导致某些项被跳过。
修复方法
# 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 与 ==
问题
# 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)
规则
- 使用
==比较值 - 仅对身份(如
None、True、False等单例)使用is
# 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. 变量作用域(LEGB)
问题
# 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]
原因
lambda 捕获的是变量 i,而不是它的值。等到调用 lambda 时,i 已经是 2。
修复方法
# 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(x):
return x
functions = [partial(return_value, i) for i in range(3)]
print([f() for f in functions]) # [0, 1, 2]
UnboundLocalError
# BAD: This raises UnboundLocalError
x = 10
def increment():
x = x + 1 # Error! x is local but used before assignment
return x
# GOOD: Use global (sparingly)
def increment():
global x
x = x + 1
return x
# BETTER: Avoid global, pass as parameter
def increment(x):
return x + 1
5. 字符串拼接
隐式拼接陷阱
# Missing comma creates concatenation
items = [
"apple"
"banana" # Oops! Missing comma
"cherry"
]
print(items) # ['applebanana', 'cherry']
# CORRECT
items = [
"apple",
"banana",
"cherry",
]
混合类型
# BAD: Can't concatenate str and int
name = "User"
count = 42
# message = "Hello " + name + ", you have " + count + " messages" # TypeError!
# GOOD: Use f-strings
message = f"Hello {name}, you have {count} messages"
# GOOD: Use str()
message = "Hello " + name + ", you have " + str(count) + " messages"
6. 闭包中的延迟绑定
问题
# Class method gotcha
class MyClass:
def __init__(self, callbacks=[]): # BAD: Mutable default!
self.callbacks = callbacks
def add_callback(self, func):
self.callbacks.append(func)
obj1 = MyClass()
obj2 = MyClass()
obj1.add_callback(lambda: print("Hello"))
# obj2 also has the callback!
print(len(obj2.callbacks)) # 1
修复方法
class MyClass:
def __init__(self, callbacks=None):
self.callbacks = callbacks if callbacks is not None else []
def add_callback(self, func):
self.callbacks.append(func)
7. 布尔求值
假值
# These are all falsy
falsy_values = [
False,
None,
0,
0.0,
0j,
"",
[],
{},
set(),
range(0),
]
# Gotcha: Empty collections are falsy
data = []
if data:
print("Has data") # Not printed
else:
print("No data") # Printed
# But None and empty are different!
if data is None:
print("Is None") # Not printed
elif data == []:
print("Is empty list") # Printed
显式检查
# BAD: Ambiguous check
def process(items):
if not items: # Could be None OR empty
return
# GOOD: Be explicit about what you're checking
def process(items):
if items is None:
raise ValueError("items cannot be None")
if len(items) == 0:
return # Early return for empty list
8. 浮点精度
问题
# Floating point arithmetic isn't exact
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False!
修复方法
import math
from decimal import Decimal
# GOOD: Use math.isclose for comparisons
print(math.isclose(0.1 + 0.2, 0.3)) # True
# GOOD: Use Decimal for financial calculations
price = Decimal("19.99")
tax = Decimal("0.0875")
total = price * (1 + tax)
print(total) # 21.739125
# Round appropriately
print(round(total, 2)) # 21.74
9. 异常处理
裸 except
# BAD: Catches everything, including KeyboardInterrupt
try:
risky_operation()
except:
pass
# BAD: Too broad
try:
risky_operation()
except Exception:
pass # Silently ignores all errors
# GOOD: Catch specific exceptions
try:
risky_operation()
except ValueError as e:
logger.error(f"Invalid value: {e}")
except ConnectionError as e:
logger.error(f"Connection failed: {e}")
raise # Re-raise after logging
异常变量作用域
# Python 3: Exception variable is deleted after except block
try:
1 / 0
except ZeroDivisionError as e:
error = e # Save if needed
print(e)
# print(e) # NameError! e is deleted
print(error) # OK
10. 字典键的顺序
现代 Python(3.7+)
# Since Python 3.7, dicts maintain insertion order
d = {"b": 2, "a": 1, "c": 3}
print(list(d.keys())) # ['b', 'a', 'c'] - insertion order
# But comparison ignores order
d1 = {"a": 1, "b": 2}
d2 = {"b": 2, "a": 1}
print(d1 == d2) # True
陷阱:遍历时修改字典
# BAD: RuntimeError
d = {"a": 1, "b": 2, "c": 3}
for key in d:
if d[key] == 2:
del d[key] # RuntimeError: dictionary changed size during iteration
# GOOD: Iterate over copy of keys
d = {"a": 1, "b": 2, "c": 3}
for key in list(d.keys()):
if d[key] == 2:
del d[key]
print(d) # {'a': 1, 'c': 3}
# GOOD: Dict comprehension
d = {"a": 1, "b": 2, "c": 3}
d = {k: v for k, v in d.items() if v != 2}
11. 导入陷阱
循环导入
# module_a.py
from module_b import func_b # Fails if module_b imports from module_a
def func_a():
return func_b()
# SOLUTION: Import inside function
def func_a():
from module_b import func_b
return func_b()
# OR: Import module, not function
import module_b
def func_a():
return module_b.func_b()
模块名称遮蔽
# BAD: File named random.py shadows stdlib
# random.py (your file)
import random # Imports YOUR file, not stdlib!
random.randint(1, 10) # AttributeError
# Python 3.13 now warns about this!
12. 类属性与实例属性
class MyClass:
shared_list = [] # Class attribute - shared by all instances!
def add_item(self, item):
self.shared_list.append(item)
a = MyClass()
b = MyClass()
a.add_item("hello")
print(b.shared_list) # ['hello'] - Oops!
# GOOD: Initialize in __init__
class MyClass:
def __init__(self):
self.items = [] # Instance attribute - unique to each instance
def add_item(self, item):
self.items.append(item)
快速参考
| 易踩的坑 | 问题 | 解决方案 |
|---|---|---|
| 可变默认值 | def f(x=[]) | 使用 None,并在函数中创建 |
| 遍历时修改 | 跳过条目 | 遍历副本或使用推导式 |
is 与 == | 身份与相等性 | 仅对 None、True、False 使用 is |
| 延迟绑定 | 捕获变量而非值 | 使用默认参数捕获值 |
| 假值 | 空值不等于 None | 在检查时明确指定 |
| 浮点精度 | 0.1 + 0.2 != 0.3 | 使用 math.isclose() 或 Decimal |
裸 except | 捕获范围过广 | 捕获特定异常 |
| 字典遍历 | 遍历期间不能修改 | 遍历 list(d.keys()) |
| 循环导入 | 导入错误 | 在函数内导入或导入模块 |
| 类属性 | 意外共享 | 在 __init__ 中初始化 |
评论
支持 Markdown