The Bug I Hit When I Forgot a return in Python
- August 24, 2025
- Python programming
I once hit a sneaky Python bug: my function kept returning None when I expected a value.
The mistake? I simply forgot to add the return keyword.
Here’s a simplified example similar to my bug:
1def get_data():
2 # Intended to return a list
3 [1, 2, 3] # Oops! Missing 'return' here
​
Why Python Functions Return None
At first glance, it looks like get_data() returns the list [1, 2, 3]. But actually, Python function returned None! Why?
- In Python, no
return,return, andreturn Noneare all equivalent — they all result inNone. - Writing an expression alone (like
[1, 2, 3]) withoutreturndoes nothing with the value — it’s just evaluated and discarded.
This behavior is obvious once you know it, but it’s easy to slip up if you also use languages like Rust, where the last expression in a function is implicitly returned.
That muscle memory can lead straight into this bug in Python.
Functions can have multiple return points:
1def example(x):
2 if x > 0:
3 return x
4 else:
5 return -x
Python exits at the first encountered return statement during execution.
If any execution path reaches the end of the function without hitting a return, Python returns None:
1def maybe_return(x):
2 if x > 0:
3 return x
4 # no else branch and no return at the end
5
6print(maybe_return(5)) # prints 5
7print(maybe_return(-1)) # prints None
This can lead to bugs if your code expects a non-None value but gets None unexpectedly.
Tip
​
Lessons learned
- Always use
returnexplicitly when you want to return a value. - Be mindful that a Python function returns
Noneby default if you forgetreturn— and that noreturn,return, andreturn Noneall mean the same thing. - If you also use Rust or similar languages, remember that Python won’t return the last expression automatically.
- Consider adding type hints and using static analysis tools (for example,
ty).
I’ve listed more options in my Python learning resources article, which can help catch missing returns.
1def maybe_return(x: int) -> int | None:
2 if x > 0:
3 return x
4 # no return if x <= 0
- Write unit tests covering all branches to detect unexpected
Nonevalues early.
Hope this helps you avoid the tiny but tricky mistake of a Python function returning None when you forgot return!
Newsletter
Subscribe to our newsletter and stay updated.