November 14, 2026
5 Python Bugs That Look Correct Until You Test Them
Consider this:

By Priyanshu Rajput
5 min read
import os
debug = bool(os.getenv("DEBUG", "false"))import os
debug = bool(os.getenv("DEBUG", "false"))You set DEBUG=false, start your application, and discover that debug mode is enabled.
The code looks reasonable. It reads an environment variable and converts it to a boolean. But Python doesn't interpret the word "false" as a boolean value. It simply checks whether the string is empty.
Since "false" is a nonempty string, bool("false") returns True.
This is a small mistake, but it highlights a bigger problem: code can look perfectly reasonable, pass a basic test, and still behave incorrectly under different conditions.
This is particularly important when reviewing AI-generated Python code. An AI assistant can produce code that looks clean and even include tests that pass. But those tests may only verify the exact scenario the code was written for.
Let's look at five common Python mistakes and, more importantly, how to catch them.
1. The Default Argument That Remembers Previous Calls
Consider a function that adds a tag to a list:
def add_tag(tag, tags=[]):
tags.append(tag)
return tags
print(add_tag("python"))
# ['python']
print(add_tag("ai"))
# ['python', 'ai']def add_tag(tag, tags=[]):
tags.append(tag)
return tags
print(add_tag("python"))
# ['python']
print(add_tag("ai"))
# ['python', 'ai']You might expect the second call to return ['ai'].
Instead, it also contains 'python'.
Why?
Python creates the default list only once, when the function is defined, not every time the function is called.
Every call that doesn't provide its own list uses the same list.
This means the function unintentionally remembers data from previous calls.
The fix is simple: use None as the default and create a new list inside the function.
def add_tag(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tags
print(add_tag("python"))
# ['python']
print(add_tag("ai"))
# ['ai']def add_tag(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tags
print(add_tag("python"))
# ['python']
print(add_tag("ai"))
# ['ai']Now each call gets its own list unless the caller explicitly provides one.
What to test: Call the function twice without providing the optional argument. A single call won't reveal this bug.
2. When Zero Accidentally Becomes the Default
Imagine a configuration where users can specify how many times an operation should be retried.
config = {"retries": 0}
retries = config.get("retries") or 3
print(retries)
# 3config = {"retries": 0}
retries = config.get("retries") or 3
print(retries)
# 3The user explicitly set retries to 0, meaning they don't want any retries.
But the application silently changes it to 3.
The problem is this expression:
config.get("retries") or 3config.get("retries") or 3In Python, or doesn't check whether a value exists. It checks whether the value is truthy.
These values are considered falsy:
bool(0) # False
bool(False) # False
bool("") # False
bool([]) # False
bool(None) # Falsebool(0) # False
bool(False) # False
bool("") # False
bool([]) # False
bool(None) # FalseSo when retries is 0, Python evaluates the expression as 0 or 3 and returns 3.
If you only want the default when the key is missing, use:
retries = config.get("retries", 3)retries = config.get("retries", 3)Now:
print(config.get("retries", 3))
# 0
print({}.get("retries", 3))
# 3print(config.get("retries", 3))
# 0
print({}.get("retries", 3))
# 3If None should also trigger the default, handle it explicitly:
retries = config.get("retries")
if retries is None:
retries = 3retries = config.get("retries")
if retries is None:
retries = 3What to test: Always test zero when working with numeric configuration values. Zero is a valid value, not necessarily a missing one.
3. The Generator That Disappears After One Use
Consider a function that calculates the average of a collection of numbers:
def average(values):
total = sum(values)
count = sum(1 for _ in values)
return total / count
print(average([10, 20, 30]))
# 20.0def average(values):
total = sum(values)
count = sum(1 for _ in values)
return total / count
print(average([10, 20, 30]))
# 20.0Everything works.
Now let's pass the exact same numbers using a generator:
values = (x for x in [10, 20, 30])
print(average(values))
# ZeroDivisionErrorvalues = (x for x in [10, 20, 30])
print(average(values))
# ZeroDivisionErrorWhy does changing the input format break the function?
Because a generator can only be consumed once.
The first sum() iterates through all its values. When the second sum() tries to count them, the generator is already exhausted.
There are no values left to count.
One solution is to convert the input into a list, but that requires storing all the values in memory.
A better solution for calculating an average is to iterate only once:
def average(values):
total = 0
count = 0
for value in values:
total += value
count += 1
if count == 0:
raise ValueError("Cannot average an empty input")
return total / count
print(average([10, 20, 30]))
# 20.0
print(average(x for x in [10, 20, 30]))
# 20.0def average(values):
total = 0
count = 0
for value in values:
total += value
count += 1
if count == 0:
raise ValueError("Cannot average an empty input")
return total / count
print(average([10, 20, 30]))
# 20.0
print(average(x for x in [10, 20, 30]))
# 20.0This works with both lists and generators without requiring multiple iterations.
It also handles empty input explicitly.
What to test: If a function accepts an iterable, test it with both a list and a generator. They may contain identical values but behave differently.
4. Three Functions, One Shared Value
Look at this code:
checks = [
lambda value: value > limit
for limit in (10, 20, 30)
]
print([check(25) for check in checks])
# [False, False, False]checks = [
lambda value: value > limit
for limit in (10, 20, 30)
]
print([check(25) for check in checks])
# [False, False, False]You might expect:
[True, True, False][True, True, False]After all, the three functions are supposed to check whether a value is greater than 10, 20, and 30 respectively.
But all three return False.
The reason is something called late binding.
The lambda functions don't capture the value of limit when they are created. Instead, they look up that variable when they are executed.
By the time the functions run, the loop has finished, and limit has the value 30.
As a result, all three functions effectively perform:
lambda value: value > 30lambda value: value > 30One way to fix this is to capture the current value using a default argument:
checks = [
lambda value, limit=limit: value > limit
for limit in (10, 20, 30)
]
print([check(25) for check in checks])
# [True, True, False]checks = [
lambda value, limit=limit: value > limit
for limit in (10, 20, 30)
]
print([check(25) for check in checks])
# [True, True, False]Another approach is to use a function factory:
def above(limit):
def check(value):
return value > limit
return check
checks = [above(limit) for limit in (10, 20, 30)]
print([check(25) for check in checks])
# [True, True, False]def above(limit):
def check(value):
return value > limit
return check
checks = [above(limit) for limit in (10, 20, 30)]
print([check(25) for check in checks])
# [True, True, False]The factory creates a separate scope for each threshold, making the intent easier to understand.
What to test: When creating callbacks inside loops or comprehensions, execute them after the loop finishes. Testing them only during creation won't reveal late binding.
5. The Boolean String That Always Returns True
Let's return to the problem from the beginning.
import os
debug = bool(os.getenv("DEBUG", "false"))
print(debug)
# Trueimport os
debug = bool(os.getenv("DEBUG", "false"))
print(debug)
# TrueEven if the environment variable is set to "false", the result is True.
The reason is that environment variables are strings, and Python doesn't automatically interpret strings as boolean values.
For example:
bool("true") # True
bool("false") # True
bool("0") # True
bool("no") # True
bool("") # Falsebool("true") # True
bool("false") # True
bool("0") # True
bool("no") # True
bool("") # FalsePython only checks whether the string is empty.
The correct approach is to explicitly define which values represent True and False.
def parse_bool(value):
if isinstance(value, bool):
return value
if isinstance(value, str):
value = value.strip().lower()
if value in {"true", "1", "yes"}:
return True
if value in {"false", "0", "no"}:
return False
raise ValueError(f"Invalid boolean value: {value!r}")def parse_bool(value):
if isinstance(value, bool):
return value
if isinstance(value, str):
value = value.strip().lower()
if value in {"true", "1", "yes"}:
return True
if value in {"false", "0", "no"}:
return False
raise ValueError(f"Invalid boolean value: {value!r}")Now we can safely parse environment variables:
debug = parse_bool(os.getenv("DEBUG", "false"))debug = parse_bool(os.getenv("DEBUG", "false"))And test different inputs:
assert parse_bool("true") is True
assert parse_bool("false") is False
assert parse_bool(" YES ") is True
assert parse_bool("0") is False
parse_bool("maybe")
# ValueErrorassert parse_bool("true") is True
assert parse_bool("false") is False
assert parse_bool(" YES ") is True
assert parse_bool("0") is False
parse_bool("maybe")
# ValueErrorNotice that invalid values raise an exception instead of silently becoming True or False.
This is important for configuration. A typo in an environment variable should be discovered immediately, not silently change application behavior.
What to test: Test both representations of a boolean, including "false", "0", and unexpected strings. Never assume that converting a string to bool parses its meaning.
The Real Lesson: Test What Could Go Wrong
None of these examples is particularly complicated. That's exactly why they're easy to overlook.
The problem isn't necessarily that the code is poorly written. The problem is that it makes assumptions that haven't been tested.
Consider what the first test might miss in each case:
CodeWhat the obvious test missesDefault argumentsA second function callDictionary defaultsA value of 0GeneratorsAn exhausted iteratorLambda callbacksExecution after the loopBoolean conversionA string containing "false"
The next time you review code, especially code generated by an AI assistant, don't stop when the example works.
Try asking:
"What assumptions does this function make about its inputs, state, and execution? Give me an example that would break each assumption."
Then run those examples yourself.
A good test doesn't just prove that your code works. It helps reveal the conditions under which it doesn't.