Posts

Assert in Python: Patterns for Cleaner Python

Sometimes a genuinely helpful language feature gets less attention than it deserves. For some reason, this is what happened to Python’s built-in assert statement. In this chapter I’m going to give you an introduction to using assertions in Python. You’ll learn how to use them to help automatically detect errors in your Python programs. This will make your programs more reliable and easier to debug. At this point, you might be wondering “What are assertions and what are they good for?” Let’s get you some answers for that. At its core, Python’s assert statement is a debugging aid that tests a condition. If the assert condition is true, nothing happens, and your program continues to execute as normal. But if the condition evaluates to false, an AssertionError exception is raised with an optional error message. Assert in Python —An Example Here’s a simple example so you can see where assertions might come in handy. I tried to give this some semblance of a real-world problem you might actua...