Python's Truthiness: A Code Smell Worth Sniffing
owl.billpg.com·4d·
Discuss: Hacker News
Flag this post

Python lets you use any value in if and while conditions, not just Booleans. This permissiveness relies on a concept known as “truthiness”. Values like None, 0, "", and empty collections are treated as false and everything else is true.

It’s convenient. It’s idiomatic. It’s also, I argue, a code smell.

The Bug That Changed My Mind

Here’s a real example from one of my side projects:

def final_thing_count() -> Optional[int]:
"""Returns an integer count of things, but only
if the number of things is complete. If there may
yet be things to come, returns None to indicate
the count isn't final."""
# Code Redacted.

current_thing_count: Optional[int] = final_thing_count()
if current_thing_count:
# Process the final count of things.

Looks fine, right? But it’s bro…

Similar Posts

Loading similar posts...