On-screen text
9 Python Mistakes
Everyone Makes
Write cleaner, faster,
more Pythonic code
01 MISTAKE
Mutable Default Args
DON'T
def add(val, items=[]):
items.append(val)
return items
DO THIS
def add(val, items=None):
items = []
items.append(val)
return items
Default [] is shared across
every call and mutates silently.
WHY
Python creates the default once at function definition,
not per call.
02 MISTAKE
Bare except: Clauses
DON'T
try:
process(data)
except:
pass
DO THIS
try:
process(data)
except ValueError as e:
logger.error(e)
Bare except: catches
everything, including Ctrl+C.
WHY
It swallows SystemExit, KeyboardInterrupt, and hides
real bugs.
03 MISTAKE
Checking == None
DON'T
if user == None:
return "anonymous"
DO THIS
if user is None:
return "anonymous"
Use is None for identity checks, not equality.
WHY
== calls __eq__, which can be overridden. is checks
object identity.
04 MISTAKE
Skipping with Statements
DON'T
f = open("data.csv")
data = f.read()
f.close()
DO THIS
with open("data.csv") as f:
data = f.read()
Context managers guarantee
cleanup, even on exceptions.
WHY
If an exception fires before .close(), the file handle
leaks.
05 MISTAKE
String += In Loops
DON'T
result = ""
for w in words:
result += w
DO THIS
result = "".join(words)
Each += copies the entire string. That's O(n²).
WHY
Strings are immutable. join() allocates once, += copies
every time.
06 MISTAKE
The range(len()) Habit
DON'T
for i in range(len(items)):
print(items[i])
DO THIS
for i, val in enumerate(items):
print(val)
enumerate() gives index +
value with zero overhead.
WHY
Cleaner, less error-prone, and the Pythonic way to
iterate.
07 MISTAKE
Wildcard import *
DON'T
from os.path import *
DO THIS
from os.path import join, exists
Dumps every name into your namespace blindly.
WHY
Causes silent name collisions and makes code
impossible to trace.
08 MISTAKE
Not Using f-strings
DON'T
msg = "Hi " + name + ", " + "age " + str(age)
DO THIS
msg = f"Hi {name}, age {age}"
f-strings are faster, shorter, and easier to scan.
WHY
Concat is error-prone and slow. f-strings inline
expressions directly.
09 MISTAKE
type() For Type Checks
DON'T
if type(x) == int:
total += x
DO THIS
if isinstance(x, int):
total += x
isinstance() respects
inheritance. type() does not.
WHY
A bool is an int subclass. type(True) == int is False,
isinstance works.
Follow For More
Python & Coding
Content