01 / 21
>_

Common Python
Edge Cases

Master the subtle traps that catch even experienced developers: integer division, mutable defaults, and None handling.

Python

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

// Integer Division
Floor division truncates toward negative infinity, not toward zero.
[ ] Mutable Defaults
Default mutable arguments are shared across all calls to a function.
None Handling
None is not zero, not empty, and not False: confusing them leads to bugs.

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.

Syntax Error Easy to find Runtime Error Crashes visibly Silent Bug Wrong output ← Easier to debug · · · Harder to debug → Edge cases live here

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.

# Positive numbers: no surprise 7 // 2 # → 3 (rounds 3.5 down to 3) # Negative numbers: the trap! -7 // 2 # → -4 (rounds -3.5 down to -4, NOT -3)

Floor vs Truncation

-4 -3 0 3 4 -3.5 3.5 floor: -4 floor: 3 trunc: -3 trunc: 3 Python // (floor) C / Java (truncate)

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.

def add_item(item, items=[]): items.append(item) return items print(add_item("a")) # → ['a'] print(add_item("b")) # → ['a', 'b'] ← BUG! print(add_item("c")) # → ['a', 'b', 'c'] ← BUG!

How Mutable Defaults Actually Work

Function Object add_item.__defaults__ ['a','b','c'] Same object every call! Call 1: "a" → ['a'] Call 2: "b" → ['a','b'] Call 3: "c" → ['a','b','c'] ✓ The Fix: Use None as sentinel def add_item(item, items=None): if items is None: items = []

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.

# These are ALL falsy, but they are NOT None: bool(0) # → False bool("") # → False bool([]) # → False bool(None) # → False # The dangerous pattern: if not value: # catches 0, "", [], AND None if value is None: # catches ONLY None ← CORRECT

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

1
Audit your division. Whenever you use // or %, ask: "Can the operands be negative?" If yes, use int(a / b) for truncation toward zero.
2
Never use mutable defaults. Replace def f(x=[]) with def f(x=None) and create the mutable inside the function body.
3
Test for None explicitly. Always write if x is None, never if not x when you mean to check for None specifically.
4
Test with edge inputs. Include 0, -1, "", [], and None in your test cases.

Example 1: Pagination Bug

You have items = -7 (a debt offset) and page_size = 2. Calculate how many pages you need.

✕ Buggy
pages = -7 // 2 # → -4 (wrong!) # Expected: -3
✓ Fixed
pages = int(-7 / 2) # → -3 (correct!) # Truncates toward zero

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.

✕ Buggy
def new_cart(item, cart=[]): cart.append(item) return cart new_cart("apple") # → ['apple'] new_cart("bread") # → ['apple','bread'] # Customer 2 got # customer 1's items!
✓ Fixed
def new_cart(item, cart=None): if cart is None: cart = [] cart.append(item) return cart new_cart("apple") # → ['apple'] new_cart("bread") # → ['bread'] ✓

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.

✕ Buggy
def get_config(key): val = config.get(key) if not val: return "default" return val # config["timeout"] = 0 # → "default" (WRONG!) # 0 is a valid timeout
✓ Fixed
def get_config(key): val = config.get(key) if val is None: return "default" return val # config["timeout"] = 0 # → 0 ✓ (correct!) # Only None → default

Common Mistakes to Watch For

✕ Using // for Truncation
Python's // floors, not truncates. With negatives, -7 // 2 gives -4, not -3.
✕ Mutable Default Args
Using def f(x=[]) shares the same list across all calls. Use None sentinel instead.
✕ Checking None with ==
Using == None can give false positives if a class overrides __eq__. Always use is None.
✕ Truthiness for None
Writing if not x catches 0, "", [], and False along with None.

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

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

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?