GUIDE深度 · Deep dive
Common Python Traps
Many Python bugs come from code that looks right. Mutable default arguments, shallow copies, is versus ==, integer division and floating-point error are common traps; predict the output, then run it.
Four common traps
def f(x=[]): the default list is created once.
y = x is not a copy; mutating y affects x.
is compares identity; == compares values.
0.1 + 0.2 != 0.3 due to floating-point error.
How to avoid
Use None as the default and create the list inside.
Use copy(), slicing or deepcopy for independent lists.
FAQ
Why is 0.1+0.2 not 0.3?
Binary floats cannot represent 0.1 exactly; compare with math.isclose.
When should I use is?
Comparing with None/True/False, or when identity really matters.