3 Inscrutable Python Bugs: Mistakes You Can Avoid

Dissecting 3 unexpected Python behaviors.

Peter Barrett Bryan
Python in Plain English

--

Photo by Markéta Marcellová on Unsplash

To celebrate three years as a Python developer, I’d like to share three of my favorite bugs! The primary criterion for this list was the “number of hours spent tearing out hair.” Hopefully, this article spares you some debugging!

1. Mutable defaults

In a Python function definition, you can define a default value for a parameter to assume if no other value is provided. Commonly, the empty list is provided as the default for an iterable argument. Be careful, though! The reference to the default is preserved across function calls. This means that any changes to the object— such as appended values — will be persistent!

2. Assertion syntax

Python assertions provide an easy mechanism to check values to avoid tricky edge conditions. If the truth value of an assertion doesn’t hold, an AssertionError is raised. The syntax, though, provides an easy snag. If the asserted truth condition and the string value are supplied in parentheses, they are interpreted as a tuple. Unfortunately, Python interprets non-None values (like tuples) as truthy. The assertion on line 21 will never be called, even if the divisor argument is 0!

3. Cache modification

LRU cache is a handy way to speed up functions that are repeatedly called… provided that the return values are deterministic (strictly specified by the arguments) and cannot be modified by reference. Rather than computing the output on each call, Python caches the returned value. The lru_cache decorator imported from functools supports syntactically elegant memoization. If an object is modified, however, it will be persisted across call to the cached function.

Leave a comment or a clap if you’ve learned something! I’m thinking about making a series if folks are interested!

More content at plainenglish.io. Sign up for our free weekly newsletter. Get exclusive access to writing opportunities and advice in our community Discord.

--

--

Software engineer with specializations in remote sensing, machine learning applied to computer vision, and project management.