Skip to content
Common Python Mistakes: Mutable Default Arguments, Class Variables, and Exception Syntax
Fundamentals 5 min read

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 Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle

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:

def foo(bar=[]):
    bar.append("baz")
    return bar

>>> foo()
['baz']
>>> foo()
['baz', 'baz']
>>> foo()
['baz', 'baz', 'baz']

The fix is to use None as the sentinel and create a new list inside the function:

def foo(bar=None):
    if bar is None:
        bar = []
    bar.append("baz")
    return bar

>>> foo()
['baz']
>>> foo()
['baz']
>>> foo()
['baz']

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:

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

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:

try:
    l = ["a", "b"]
    int(l[2])
except (ValueError, IndexError) as e:
    pass

Applying these corrected patterns eliminates the confusing behavior demonstrated in the original examples.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythonexception-handlingmutable objectsClass Variablesdefault-arguments
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.