Lesson · Idiomatic Python & Code Quality
Common Python Traps
64 min readCommon Python Traps
Python has a small set of recurring traps that mostly come from misunderstanding binding, mutability, identity, iteration, and floating-point behavior. Learning the underlying model is better than memorizing warnings.
Learning goals
- Predict why
def bad(item, items=[])keeps growing: the default list is created once when thedefstatement runs and every call without that argument shares it. - Explain why closures built in a loop all see the final loop value, and fix the pattern with a default parameter such as
lambda i=i: i. - Use
isfor identity (singletons such asNone, sentinel objects) and==for values, and say what each operator compares. - Show why
[[0] * 3] * 3aliases one inner list and rewrite it with a comprehension that creates three distinct rows. - Explain why
0.1 + 0.2 == 0.3isFalseand what to compare with instead.
Mental model
All of these traps are consequences of two facts: objects are created at a specific moment, and names (including default parameters and closure variables) refer to those objects rather than holding copies. When the creation moment is earlier than you expected, at the def line or before a loop starts, the second call or the second row sees the first one's object. Tracing which line created the object, and who else points at it, predicts the behavior in every case in this lesson.
Mental model
read it top to bottom
one root cause: names point at objects, and objects have lifetimes ↓ objects created once, not once per call or per row: default arguments, [row] * n, loop variables captured by closures ↓ objects shared by reference: shallow copies, aliased inner lists ↓ the identity question: is (same object) versus == (equal value)
Core idea
The traps in this lesson are the object model acting exactly as documented when a name, a default value, or a multiplied list keeps an object alive longer than the author expected. The dependable habit is mechanical: find the moment the object is created, list every name that refers to it, then decide whether the code needs a fresh object per call, per row, or a value comparison instead of an identity check.
Mutable default arguments
A mutable default argument is a value such as [] or {} in a function signature that is created once, when the def statement executes, and then shared by every call that omits that argument. Mutation inside one call therefore persists into later calls, which is why def bad(item, items=[]) returns [1] and then [1, 2]. The standard repair is a None default with an explicit items = [] if items is None else items in the body.
Late-binding closures
A closure keeps references to names from an enclosing function scope after that outer call has returned. The captured binding, not a frozen snapshot of its value, is what matters.
is vs ==
is asks whether two names refer to the same object (identity), while == asks whether two objects consider themselves equal in value. Use is for singletons such as None and sentinel objects, and == for numbers, strings, and every other value comparison. is sometimes seems right for small integers or short strings because CPython caches those objects, but that caching is an implementation detail, not a language guarantee.
Modifying collections during iteration
Modifying a collection while iterating it makes the iteration's position disagree with the data: a list keeps advancing by index while a removal shifts later elements left (so some are skipped), and a dictionary raises RuntimeError: dictionary changed size during iteration. The safe pattern builds a new collection with a loop or comprehension, or collects the changes and applies them after the loop. Deciding first whether you are filtering or updating in place is what makes the rewrite straightforward.
Shallow-copy surprises
A shallow copy creates a new outer container whose elements are references to the same objects the original held, so nested mutables stay shared: copy.copy on a list of lists leaves the inner lists aliased. A deep copy (copy.deepcopy) recursively copies the nested objects, at a cost that grows with the structure. Choose based on whether the nested objects are immutable (strings, tuples of numbers) or shared on purpose.
Nested-list multiplication
[[0] * 3] * 3 multiplies references, not rows: the expression builds one inner list, then an outer list holding three references to that single object, so writing to grid[0][0] is visible through every row. The comprehension form [[0] * 3 for _ in range(3)] evaluates the inner expression once per row and creates three distinct lists. Checking grid[0] is grid[1] separates the two cases immediately.
Broad exception catching
An except Exception clause (or a bare except) converts every failure inside the try into the same outcome, including a NameError from a typo in the fallback code and errors that should have stopped the program. Naming the expected exception, such as KeyError or FileNotFoundError, keeps unrelated bugs visible and documents what the try block is prepared to handle. When several types genuinely share one recovery, list them in the except clause instead of widening to Exception.
Floating-point equality
Binary floating point cannot represent most decimal fractions exactly: 0.1 and 0.2 are each stored as the nearest available double, so their sum is close to, but not equal to, the stored 0.3, and == returns False. Compare computed floats with math.isclose using a tolerance that fits the domain, or round both sides before the check. Print with repr() when inspecting a float, because it shows the shortest string that maps back to the same binary value.
Import side effects
Importing a module executes its top-level code once, then caches the module in sys.modules, so side effects such as opening files or starting threads run on the first import only and never again for that process. Code that must run repeatedly belongs in functions, and code that must run as a program belongs behind if __name__ == "__main__":. Keeping module-level code free of heavy side effects also avoids circular-import problems and makes the module testable.
Shadowing built-ins
Shadowing binds a local name that hides an outer or built-in name during lookup. It is legal but can make code harder to understand when the hidden name is widely recognized.
Walkthrough
- The
def badline is whenitems=[]runs: the list is created once at function definition, not once per call.bad(1)appends to that list and returns it, so the second call receives the same list already holding[1]and prints[1, 2]; nothing resets the default. [[0] * 3] * 3builds one inner list and an outer list whose three slots all refer to that same inner object.grid[0][0] = 9mutates the shared row, so all three rows print as[9, 0, 0], which shows the aliasing in a single line.- The two traps share a mechanism: a value that should be per-call or per-row was created once, and multiple names hold references to it.
bad(1)andbad(2)shareitems;grid[0],grid[1], andgrid[2]share the inner list. - Predict before running: the output of
print(bad(1))andprint(bad(2)), and how many distinct list objectsgridcontains after the assignment.
Experiments to try
- Call
bad(3, [])with an explicit list and confirm the shared default is untouched; then change the signature toitems=Nonewithitems = [] if items is None else itemsinside the body and verify thatbad(1)andbad(2)now print single-item lists. - Compare
grid[0] is grid[1]for the multiplied grid (True) and for[[0] * 3 for _ in range(3)](False), then repeat the assignment and confirm only one row changes in the comprehension version. - Create
funcs = [lambda: i for i in range(3)]and print every result (all 2), then rebuild withlambda i=i: iand record the change. - Remove the even numbers from
[1, 2, 3, 4, 5, 6]withfor n in numbers: if n % 2 == 0: numbers.remove(n)and record which elements survive; rewrite it as a comprehension over a new list and compare the results.
Common mistakes
- Defending
items=[]with "it is just a default": the default is evaluated once when thedefstatement executes, so the function is silently stateful and calls leak into each other while the signature still looks fresh. - Using
isfor value comparison because it passes for small integers and short strings:iscompares object identity, and CPython's caching of those objects is an implementation detail, so the same check can fail for a larger number or a runtime-built string; use==unless the question is identity. - Fixing the nested-list alias with
copy.copy: the shallow copy gives the outer list new storage but copies the inner references, soshallow[0][0] = 9still changes every row; the fix must create new inner objects, as[[0] * 3 for _ in range(3)]orcopy.deepcopydoes. - Comparing floats with
==after arithmetic:0.1 + 0.2is the nearest double to 0.3 but not the double literal0.3, so the comparison fails with no arithmetic mistake; compare withmath.iscloseand a tolerance that fits the domain.
Practice: Easy
- Run the worked example as written and record both printed results; then change the signature to
items=Nonewith explicit list creation and rerunbad(1)andbad(2). - Check
grid[0] is grid[1]andgrid[0] == grid[1]for the multiplied grid; rebuild with a comprehension, repeat the assignment, and confirm onlygrid[0]changes. - Print the results of
[lambda: i for i in range(3)]and of thelambda i=i: iversion; write one sentence for what each closure captured.
Practice: Medium
- Rewrite a loop that builds lambdas so each one captures its own value, using either a default parameter or a factory function, and prove the fix by printing every stored result.
- Remove the even numbers from
[1, 2, 3, 4, 5, 6]withforplusremove, record which elements survive, then rewrite the task as a comprehension and compare both outputs. - Reproduce a shallow-copy bug:
rows = [[0] * 2] * 2,backup = rows.copy(), thenbackup[0][0] = 9; check whetherrowschanged and rebuild the backup so its inner lists are distinct objects.
Practice: Hard
- Build a trap lab with four minimal snippets, one for each of mutable defaults, aliased rows, loop closures, and float equality; write the predicted output as a comment before each run, then annotate every mismatch with the object mechanism behind it.
- Audit a small class that uses a class-level
items = []and a method default of{}: demonstrate both shared-state bugs, fix them (instance attribute created in__init__,Nonedefault), and add one test per bug that would have caught it. - Refactor a float comparison that uses
==on computed values intomath.isclosewith a domain-appropriate tolerance, then explain when an exact comparison is still legitimate (values assigned directly, never computed).
Lesson checklist
- I can explain when a default argument's value is created and why that makes
items=[]shared state. - I can fix a loop of closures with a default parameter and say what the original version captured.
- I can choose
isor==from the question (same object or same value) and defend the choice. - I can spot an aliased nested structure and rebuild it so every row is a distinct object.
Remember
The traps in this lesson all reduce to object lifetimes and aliasing: defaults, closures, and multiplied lists each create one object at a moment the author did not intend, and every later use shares it. Read the symptom backwards to the mechanism by asking which line created the object and who still refers to it, and the fix (a `None` default, a fresh comprehension, a value comparison) becomes obvious.
Interview angles
What is the main purpose of **Mutable default arguments**?+
The default items=[] is evaluated once, when the def statement runs, and every call that omits the argument receives that same list, so bad(1) then bad(2) prints [1] and then [1, 2]. Use None as the default and create a fresh list inside the function body.
What should you pay attention to when using **Late-binding closures**?+
A closure keeps references to names from an enclosing function scope after that outer call has returned. The captured binding, not a frozen snapshot of its value, is what matters.
How does **is vs ==** fit into this lesson?+
is compares identity, asking whether two names refer to the same object, which is what you want for None and sentinels. == compares value, asking whether two objects consider themselves equal, which is what nearly every other check wants. Using is on numbers or strings only appears to work because CPython caches some of those objects.
What goes wrong when you fix `[[0] * 3] * 3` with `copy.copy`?+
The shallow copy gives the outer list new storage but copies the inner references, so the three rows still point at one inner list and shallow[0][0] = 9 still changes every row. The fix has to create a new inner list per row, as [[0] * 3 for _ in range(3)] does, or copy the structure deeply.