Fundamentals 11 min read

Master Python Defaults, Closures, and Class Variables: Common Pitfalls Explained

This article explains why mutable default arguments share state, how Python closures cause late binding issues, the inheritance rules of class variables, differences between division operators in Python 2 and 3, list slicing behavior, list multiplication references, list comprehensions for even-indexed values, and custom dict subclasses with __missing__.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python Defaults, Closures, and Class Variables: Common Pitfalls Explained

1. The function def extendList(val, list=[]): demonstrates that a mutable default argument is created only once at function definition, causing subsequent calls without an explicit list to share the same list. The output is list1 = [10, 'a'], list2 = [123], list3 = [10, 'a']. The correct fix is to use def extendList(val, list=None): and create a new list inside the function.

2. The lambda‑based multipliers() suffers from Python’s closure late‑binding: all returned functions capture the same final value of i, so [m(2) for m in multipliers()] yields [6, 6, 6, 6]. Solutions include using a generator, binding the current value as a default argument ( lambda x, i=i: i*x), or employing functools.partial.

3. Class variables are stored in the class dictionary. Accessing Parent.x, Child1.x, Child2.x shows inheritance rules: modifying a child’s attribute masks the parent’s value, while changing the parent’s attribute affects children that have not overridden it, producing the sequence 1 1 1, 1 2 1, 3 2 3.

4. In Python 2 the / operator performs integer division for two integers, while // always performs floor division. The example prints 5/2 = 2, 5.0/2 = 2.5, 5//2 = 2, 5.0//2.0 = 2.0. In Python 3 / is true division, so the results become 5/2 = 2.5 and 5.0/2 = 2.5, while // still yields floor division.

4. (continued) The from __future__ import division statement can make Python 2 behave like Python 3 for /.

5. Slicing a list with a start index beyond its length returns an empty list instead of raising IndexError, e.g., list[10:] yields [].

6. Multiplying a list of mutable objects creates references to the same object. list = [[]] * 5 produces five references to the same inner list, so appending to one element appears in all, and list.append(30) adds a new element to the outer list, resulting in [[10, 20], [10, 20], [10, 20], [10, 20], [10, 20], 30].

7. A single list comprehension can select even numbers that also occupy even positions: [x for x in lst[::2] if x % 2 == 0], which on the example list yields [10, 18, 78].

8. Defining a subclass of dict with an __missing__ method that returns an empty list allows missing keys to be handled without error, as demonstrated by DefaultDict() where accessing an absent key returns [] instead of raising KeyError.

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.

Pythonclosureslist-comprehensionlist slicingClass Variablesdefault-argumentsdict-subclasspython2-vs-3
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.