Python Pitfalls and Corner Cases
last modified November 19, 2026 Python 3.15
This tutorial explains common Python pitfalls: valid code that behaves differently from what its author intended. Each example isolates a surprising behavior and shows how to avoid relying on it.
The examples use Python 3 and the standard library; the displayed output was
verified with Python 3.15.2. They assume familiarity with functions,
comprehensions, classes, imports, and exception handling. Run each
listing with python3 using its displayed filename; the import
example uses two files together.
Implementation-specific behavior is identified explicitly; optimizations in
CPython, the most widely used Python implementation, are not language guarantees.
Mutable Default Arguments
A default argument expression is evaluated when the def statement
executes, not each time the function is called. A mutable default, such as a
list, can therefore retain changes between calls that omit that argument.
def append_shared(element, items=[]):
items.append(element)
return items
print(append_shared(1))
print(append_shared(2))
def append_fresh(element, items=None):
if items is None:
items = []
items.append(element)
return items
print(append_fresh(1))
print(append_fresh(2))
The first function reuses one list. The second uses None to mean
that no list was supplied and creates a fresh list on each such call. An
explicitly supplied list is still modified. Use is None, not
if not items, because an empty list is a valid argument. This
pattern assumes that None is not itself a meaningful input value.
$ python3 default_args.py [1] [1, 2] [1] [2]
Variable Scope in List Comprehensions
In Python 3, a comprehension's loop variable does not overwrite a variable of
the same name outside the comprehension. A regular for loop,
however, assigns its target in the surrounding scope.
x = 10
numbers = [x for x in range(3)]
print(numbers)
print(x)
for x in range(3):
pass
print(x)
The comprehension leaves the outer x unchanged. The regular loop
leaves it bound to the last value it visited. Use descriptive, distinct loop
variable names rather than depending on a loop to preserve an existing binding.
This example concerns the comprehension's iteration variable, not assignment
expressions using :=, which have different scope rules.
$ python3 list_comp_scope.py [0, 1, 2] 10 2
Late Binding Closures
A closure is a function that uses bindings from an enclosing function. Those bindings are looked up when the inner function runs, not copied when it is created. This matters when several callbacks refer to the same loop variable.
def make_callbacks():
late = []
captured = []
for number in range(3):
late.append(lambda: number)
captured.append(lambda value=number: value)
return late, captured
late, captured = make_callbacks()
print([callback() for callback in late])
print([callback() for callback in captured])
All callbacks in late share the enclosing number
binding, whose final value is 2. In captured, each
default argument is evaluated during that iteration, preserving its current
integer value. The same late-binding behavior applies to functions declared
with def; it is not specific to lambda. A default
captures an object reference, not a deep copy of a mutable object.
$ python3 closures.py [2, 2, 2] [0, 1, 2]
Identity vs Equality
The == operator compares values; is checks whether two
references point to the very same object. Equal objects need not be identical.
Lists provide a reliable demonstration without depending on integer caching.
first = [1000] second = [1000] alias = first print(first == second) print(first is second) print(first is alias) missing = None print(missing is None)
The list displays create distinct objects, while assignment to
alias creates another reference to first. Use
== to compare numbers or text, and is None to test for
the singleton None. CPython caches some integers and may reuse
constants, including integers outside its small-integer cache. Consequently,
the identity of equal integer literals is not a portable test of their values.
$ python3 object_identity.py True False True True
Tuple Creation Gotcha
Parentheses alone do not create a one-element tuple: the comma is essential. Without it, parentheses only group an expression.
empty = () grouped = (1) single = (1,) print(type(empty).__name__) print(type(grouped).__name__) print(type(single).__name__) print(single)
The empty tuple is written (). For a nonempty tuple display,
commas separate the elements, with a trailing comma required for a single
element. This matters when passing a one-item sequence to an API: a grouped
string such as ("name") is still a string, not a tuple.
$ python3 tuples.py tuple int tuple (1,)
Dictionary Key Order
Dictionaries preserve insertion order in Python 3.7 and later. That does not make order part of dictionary equality: two dictionaries can compare equal while yielding their keys in different orders.
d1 = {'a': 1, 'b': 2}
d2 = {'b': 2, 'a': 1}
print(d1 == d2)
print(list(d1))
print(list(d2))
print(list(d1) == list(d2))
d1['a'] = 10
print(list(d1))
del d1['a']
d1['a'] = 1
print(list(d1))
Equality compares the key-value pairs without considering their order. Converting each dictionary to a list exposes its key iteration order, so those lists differ. Updating a key does not move it; deleting and reinserting it puts it at the end. Insertion order was a CPython 3.6 implementation detail before becoming a language guarantee in Python 3.7; earlier Python versions did not guarantee it. Insertion order is not sorted order.
$ python3 dict_order.py True ['a', 'b'] ['b', 'a'] False ['a', 'b'] ['b', 'a']
Boolean Evaluation
Truth value testing treats None, False, numeric zero,
and empty built-in containers as false. A fallback written with or
can therefore replace a valid value such as zero, not just a missing value.
values = [0, 0.0, False, '', [], (), {}, None, 'False']
for value in values:
print(f"{value!r}: {bool(value)}")
timeout = 0
print("Using or:", timeout or 30)
print("Checking None:", 30 if timeout is None else timeout)
The nonempty string 'False' is true; Python does not parse its
contents as a Boolean. The or operator returns one of its operands,
not necessarily a bool. If zero means "do not wait", the explicit
None check preserves it, while timeout or 30 does not.
$ python3 boolean.py
0: False
0.0: False
False: False
'': False
[]: False
(): False
{}: False
None: False
'False': True
Using or: 30
Checking None: 0
String Interning
String interning lets equal strings share a canonical object. Automatic
interning and constant reuse are implementation details, so the identity of two
equal strings must not determine application behavior. Explicit interning with
sys.intern makes the distinction visible without guessing which
literals the compiler will reuse.
import sys
first = sys.intern("hello world")
second = sys.intern(" ".join(["hello", "world"]))
print(first == second)
print(first is second)
Both variables retain the result of sys.intern, so they refer to
the same interned string. This is an explicit optimization, not a reason to use
is for text comparison. Two identical literals may also share one
constant even if they contain spaces. Use == regardless of string
length, contents, or construction method.
$ python3 string_interning.py True True
List Multiplication
List repetition repeats references to elements; it does not copy the elements. When an element is mutable, a change through one reference is visible through the others. This often affects nested lists used as grids.
shared = [[]] * 3 shared[0].append(1) print(shared) print(shared[0] is shared[1]) independent = [[] for _ in range(3)] independent[0].append(1) print(independent) print(independent[0] is independent[1])
The repeated list contains three references to one inner list. The comprehension
evaluates [] separately on each iteration, creating independent
inner lists. Repetition such as [0] * 3 is normally fine because
integers are immutable. Copying only the outer list with shared.copy()
would still leave the inner list shared.
$ python3 list_multiplication.py [[1], [1], [1]] True [[1], [], []] False
Garbage Collection of Cycles
Deleting a name does not necessarily destroy its object. A reference cycle occurs when objects refer back to themselves, directly or indirectly. CPython supplements reference counting with a cyclic garbage collector to reclaim unreachable cycles.
import gc
import weakref
class Node:
pass
was_enabled = gc.isenabled()
gc.disable()
try:
node = Node()
node.link = node
reference = weakref.ref(node)
del node
print("Alive before collection:", reference() is not None)
gc.collect()
print("Alive after collection:", reference() is not None)
finally:
if was_enabled:
gc.enable()
This example targets CPython. Automatic cyclic collection is temporarily
disabled to make the first observation predictable; gc.collect()
still runs a collection explicitly. A weak reference lets us observe the node
without keeping it alive. The finally block restores the previous
automatic-collection setting.
Since Python 3.4, ordinary Python objects with __del__ methods can
also be collected when they are in cycles. Finalizers are not inherently a
cause of uncollectable cycles, although object resurrection and some extension
types complicate cleanup. Collection timing is not a portable resource-management
strategy: use with for files and other resources requiring prompt
release, rather than relying on del or __del__.
$ python3 garbage_collection.py Alive before collection: True Alive after collection: False
Chained Comparisons
Comparison operators can form a chain, including equality and membership tests. A chain is not evaluated as a sequence of left-to-right Boolean results being fed into the next comparison.
print(3 > 2 > 1) print((3 > 2) > 1) print(False == False in [False]) print(False == False and False in [False]) print((False == False) in [False])
The first chain means 3 > 2 and 2 > 1. Its parenthesized
counterpart compares True with 1, which is false
because bool is a subclass of int and
True == 1. The mixed chain checks both
False == False and False in [False]. In general,
chains evaluate each middle expression only once and short-circuit when a
comparison is false. Use separate conditions or parentheses when combining
comparisons would obscure the intended meaning.
$ python3 precedence.py True False True True False
Class Variable vs Instance Variable
An attribute defined in a class body is shared through the class unless an instance supplies its own attribute of the same name. Mutating a shared list does not create a separate list for that instance.
class SharedDog:
tricks = []
first = SharedDog()
second = SharedDog()
first.tricks.append('roll over')
print(first.tricks)
print(second.tricks)
class Dog:
def __init__(self, name):
self.name = name
self.tricks = []
def add_trick(self, trick):
self.tricks.append(trick)
d1 = Dog('Fido')
d2 = Dog('Buddy')
d1.add_trick('roll over')
d2.add_trick('play dead')
print(d1.tricks)
print(d2.tricks)
Both SharedDog instances find the same class-level list, so both
see the added trick. Dog.__init__ instead creates a new list for
each instance. The important difference is mutation versus assignment:
first.tricks.append(...) mutates the object found by attribute
lookup, while self.tricks = [] assigns an instance attribute.
$ python3 class_vars.py ['roll over'] ['roll over'] ['roll over'] ['play dead']
Imports Are Cached
Importing a module is not a way to rerun its initialization. During normal
imports, Python caches modules by name in sys.modules. Place the
following two files in the same directory.
print("Initializing settings")
colors = ['blue']
The module prints a message when its top-level code executes and creates a list. The application imports the module twice, using an alias on the second import to make the shared module object visible.
import demo_settings
demo_settings.colors.append('green')
import demo_settings as settings_again
print(demo_settings is settings_again)
print(settings_again.colors)
The initialization message appears once in a fresh process. The second import
finds the cached module, including its modified list. This is not an absolute
"once per interpreter" rule: importlib.reload reexecutes module
code, and running a file as __main__ and then importing it by its
module name can execute it twice. Prefer an explicit function when an operation
needs to be repeated. Avoid filenames such as random.py or
json.py for your scripts, because they can shadow standard-library
modules on the import path.
$ python3 import_cache.py Initializing settings True ['blue', 'green']
Exception Scope
The name bound by except ... as is cleared when the handler ends.
This also removes any earlier binding of that name; it is not restored after
the handler. Save information under a different name if it is needed later.
error = 42
message = None
try:
raise ValueError("oops")
except ValueError as error:
message = str(error)
print("Saved message:", message)
try:
print(error)
except NameError:
print("The exception target was cleared")
After the first handler, error is undefined at module scope, so
accessing it raises NameError. The second handler catches that
error so the demonstration finishes normally. Clearing the exception target
helps break cycles involving exceptions, tracebacks, and local variables.
Saving the message avoids retaining the traceback. If the exception object
itself is required, assign it to a different variable deliberately and be aware
that doing so can keep referenced objects alive.
$ python3 exception_scope.py Saved message: oops The exception target was cleared
Source
The official Python documentation describes the rules behind these examples:
- Default argument values
- Late binding in loop-created functions
- Built-in types: truth values, sequences, and dictionaries
- Comparisons and identity
- Explicit string interning
- Garbage collector interface
- Class and instance variables
- The import system
- The except clause
This tutorial explained how shared state, scope, identity, and evaluation rules can lead to Python bugs. Use explicit ownership and comparisons rather than depending on interpreter optimizations. For background, see Python functions, copying and references, and exception handling.
Author
List all Python tutorials.