Common Python
Edge Cases
Master the subtle traps that catch even experienced developers: integer division, mutable defaults, and None handling.
What Are Edge Cases?
An edge case is a situation where code behaves differently than expected due to unusual inputs, boundary conditions, or language-specific quirks. In Python, many edge cases come from implicit type behavior that silently produces wrong results instead of errors.
The Big Three Python Traps
Why This Matters
These three categories account for a huge share of subtle Python bugs. Understanding them is the difference between code that works on test cases and code that works in production.
Rule 1: Floor Division Truncates Down
Python's // operator performs floor division: it rounds toward negative infinity, not toward zero. This is different from integer division in C, Java, and JavaScript.
Floor vs Truncation
Rule 2: Mutable Defaults Are Shared
When you use a mutable object (like a list or dict) as a default argument, Python creates it once at function definition time. Every call that uses the default shares the same object.
How Mutable Defaults Actually Work
Rule 3: None Is Not What You Think
None is Python's null value. It is its own type (NoneType). It is falsy, but it is not the same as 0, "", [], or False.
is vs == for None Checks
| x is None | x == None | not x | |
|---|---|---|---|
| x = None | True | True | True |
| x = 0 | False | False | True |
| x = "" | False | False | True |
| x = [] | False | False | True |
| x = False | False | False | True |
How to Avoid These Traps
Example 1: Pagination Bug
You have items = -7 (a debt offset) and page_size = 2. Calculate how many pages you need.
Example 2: Shopping Cart Bug
Build a function that creates a new shopping cart and adds an item. Each customer should get their own empty cart.
Example 3: Config Parser Bug
A function reads a config value. Valid values include 0 and "". Missing keys return None. Handle the "missing" case without discarding valid falsy values.
Common Mistakes to Watch For
Summary Cheat Sheet
| Edge Case | Trap | Fix |
|---|---|---|
| Negative floor division | -7 // 2 → -4 | int(-7 / 2) → -3 |
| Negative modulo | -7 % 2 → 1 | math.fmod(-7, 2) → -1 |
| Mutable defaults | def f(x=[]) | def f(x=None) |
| None check | if not x | if x is None |
| None equality | x == None | x is None |
Question 1 of 5
What does -9 // 4 evaluate to in Python?
Question 2 of 5
Consider this function:
def make_group(name, members=[]):
members.append(name)
return members
a = make_group("Alice")
b = make_group("Bob")
What is the value of b?
Question 3 of 5
Which is the correct way to check if a variable is None in Python?
Question 4 of 5
Consider this code:
value = 0
if not value:
print("Missing!")
else:
print(f"Got: {value}")
What does this code print, and is it likely a bug?
Question 5 of 5
How do you fix a function with a mutable default argument?