Common Python Mistakes: Mutable Default Arguments, Class Variables, and Exception Syntax
This article explains three frequent Python pitfalls—using mutable objects as default arguments, unintentionally sharing class variables, and writing incorrect exception clauses—illustrates the problematic behavior with code examples, and provides the proper patterns to avoid each issue.
Python developers often fall into three classic traps: using a mutable object as a function's default argument, unintentionally sharing class variables, and writing an invalid exception clause.
When a list is used as a default value, the list is created only once at function definition time, so each call appends to the same list:
<code>def foo(bar=[]):
bar.append("baz")
return bar
>>> foo()
['baz']
>>> foo()
['baz', 'baz']
>>> foo()
['baz', 'baz', 'baz']</code>The fix is to use None as the sentinel and create a new list inside the function:
<code>def foo(bar=None):
if bar is None:
bar = []
bar.append("baz")
return bar
>>> foo()
['baz']
>>> foo()
['baz']
>>> foo()
['baz']</code>The second mistake involves class variables, which are stored in the class dictionary and shared by subclasses according to the method resolution order (MRO). Changing the variable in one subclass affects the others that inherit it:
<code>class A(object):
x = 1
class B(A):
pass
class C(A):
pass
print(A.x, B.x, C.x) # 1 1 1
B.x = 2
print(A.x, B.x, C.x) # 1 2 1
A.x = 3
print(A.x, B.x, C.x) # 3 2 3</code>Understanding that C.x resolves to A.x unless overridden prevents unexpected side‑effects.
The third pitfall is an incorrect except clause that tries to list exceptions with a comma. In Python 2.x the syntax must bind the exception to a name, and in both Python 2 and 3 the proper way to catch multiple exceptions is to use a tuple and the as keyword:
<code>try:
l = ["a", "b"]
int(l[2])
except (ValueError, IndexError) as e:
pass</code>Applying these corrected patterns eliminates the confusing behavior demonstrated in the original examples.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.