Fundamentals 12 min read

Common Python Gotchas: Default Arguments, Closures, and Class Variables Explained

This article walks through several classic Python pitfalls—including mutable default arguments, closure late binding, class variable inheritance, division operator differences between Python 2 and 3, list slicing edge cases, shared references in list multiplication, list comprehensions for even-indexed values, and custom dict subclasses—explaining why they occur and how to fix them.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Common Python Gotchas: Default Arguments, Closures, and Class Variables Explained

1. Default mutable argument

When a function defines a mutable default value, such as a list, the default object is created only once at function definition time, causing all calls that omit the argument to share the same list.

def extendList(val, list=[]):
    list.append(val)
    return list

list1 = extendList(10)
list2 = extendList(123, [])
list3 = extendList('a')
print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3

The output is:

list1 = [10, 'a']
list2 = [123]
list3 = [10, 'a']

To obtain independent lists, use None as the sentinel and create a new list inside the function.

def extendList(val, list=None):
    if list is None:
        list = []
    list.append(val)
    return list

Now the output becomes:

list1 = [10]
list2 = [123]
list3 = ['a']

2. Closure late binding in multipliers

The following code returns a list of lambda functions that multiply their argument by the loop variable i:

def multipliers():
    return [lambda x: i * x for i in range(4)]

print [m(2) for m in multipliers()]

All lambdas capture the same final value of i (3), so the printed result is [6, 6, 6, 6]. This is caused by Python’s closure late binding.

Typical fixes include:

Using a generator that yields the lambda (still suffers from the same issue unless the lambda captures i as a default argument).

Binding the current value of i as a default argument:

def multipliers():
    return [lambda x, i=i: i * x for i in range(4)]

Using functools.partial to bind the multiplier:

from functools import partial, mul

def multipliers():
    return [partial(mul, i) for i in range(4)]

3. Class variable inheritance

class Parent(object):
    x = 1

class Child1(Parent):
    pass

class Child2(Parent):
    pass

print Parent.x, Child1.x, Child2.x
Child1.x = 2
print Parent.x, Child1.x, Child2.x
Parent.x = 3
print Parent.x, Child1.x, Child2.x

The output is:

1 1 1
1 2 1
3 2 3

Explanation: class variables are stored in the class’s dictionary. Subclasses inherit the reference until they assign their own value, which creates a separate entry in the subclass dictionary.

4. Division operators in Python 2 vs Python 3

def div1(x, y):
    print "%s/%s = %s" % (x, y, x/y)

def div2(x, y):
    print "%s//%s = %s" % (x, y, x//y)

div1(5, 2)
div1(5., 2)
div2(5, 2)
div2(5., 2.)

Python 2 output:

5/2 = 2
5.0/2 = 2.5
5//2 = 2
5.0//2.0 = 2.0

In Python 3, / always performs true (floating‑point) division, while // performs floor division. The same calls in Python 3 produce:

5/2 = 2.5
5.0/2 = 2.5
5//2 = 2
5.0//2.0 = 2.0

5. List slicing beyond range

lst = ['a', 'b', 'c', 'd', 'e']
print lst[10:]

The result is an empty list [] and no IndexError is raised.

6. List multiplication and shared references

lst = [[]] * 5
lst[0].append(10)
lst[1].append(20)
lst.append(30)

Because the multiplication creates five references to the *same* inner list, the intermediate states are:

[[10], [10], [10], [10], [10]]
[[10, 20], [10, 20], [10, 20], [10, 20], [10, 20]]
[[10, 20], [10, 20], [10, 20], [10, 20], [10, 20], 30]

7. List comprehension for even values at even indices

To obtain values that are even and located at even positions (0‑based) in the original list:

[x for x in lst[::2] if x % 2 == 0]

Example:

lst = [1, 3, 5, 8, 10, 13, 18, 36, 78]
# Result: [10, 18, 78]

8. Subclassing dict with __missing__

class DefaultDict(dict):
    def __missing__(self, key):
        return []

d = DefaultDict()
d['florp'] = 127

This runs without error; when a missing key is accessed, __missing__ supplies a default empty list.

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.

Pythonlist slicing
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
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.