Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

Understanding Common Pitfalls

00:00 Understanding Common Pitfalls of assert. Even though assertions are a useful tool, they have some downsides. Like any other tool, assertions can be misused.

00:12 You’ve already seen that you should use assertions for debugging and testing code during development, and that you shouldn’t rely on assertions to provide functionality in production code. In particular, you may run into pitfalls if you use assertions for processing and validating data, handling errors, and running operations with side effects.

00:32 Another common source of issues with assertions is that keeping them enabled in production can negatively impact your code’s performance. Finally, Python has assertions enabled by default, which can confuse developers coming from other languages. In the following sections, you’ll learn about all these possible pitfalls of assertions.

00:51 You’ll also learn how to avoid them in your own Python code. You shouldn’t use assert statements to verify the user’s input or any other input data from external sources.

01:03 That’s because production code typically disables assertions, which will remove all of the verification. Suppose you’re building an online store with Python, and you need to add functionality to accept discount coupons.

01:17 You end up writing the function seen on-screen. Notice the assert statement in the first line of price_with_discount(). It’s there to guarantee that the discounted price won’t be equal to or lower than zero dollars.

01:34 The assertion also ensures that the new price won’t be higher than the product’s original price.

01:45 Now, consider the example of a pair of shoes at 25 percent off.

02:05 price_with_discount() seems to work nicely. It takes the product as a dictionary, applies the intended discount to the current price, and returns the new price.

02:14 Now, what happens when you try to apply invalid discounts? Firstly, 200 percent and secondly, 100 percent.

02:32 Applying an invalid discount raises an AssertionError that points out the violated condition. If you ever encounter this error while developing and testing your online store, then it shouldn’t be hard to figure out what happened by looking at the traceback.

02:49 The real problem with this example comes if the end user can make direct calls to price_with_discount() in production code with disabled assertions.

03:03 In this situation, the function won’t check the input value for discount, possibly accepting wrong values and breaking the correctness of the discount functionality. In general, you can write assert statements to process, validate, or verify data during development. However, if those operations remain valid in production code, then make sure to replace them with an if statement or a tryexcept block.

03:31 On-screen is a new version of price_with_discount() that uses a conditional instead of an assertion. In this new implementation, you replace the assert statement with an explicit conditional.

03:46 The function now applies the discount only if the input value is between 0 and 1. Otherwise, it raises a ValueError, signaling a problem.

03:55 Now, you can wrap up any calls to this function in a tryexcept block that catches the ValueError and sends an informative message to the users so they can take action accordingly.

04:08 On-screen, you can see the updated function in action raising a ValueError when it’s called directly with an inappropriate value.

04:44 The moral of this example is that you shouldn’t rely on the assert statement for data processing or data validation because this statement is typically turned off in production code.

04:57 Another important pitfall with assertions is that sometimes developers use them as a quick form of error handling. As a result, if the production code removes assertions, then important error checks are also removed from the code.

05:10 So keep in mind that assertions aren’t a replacement for good error handling On-screen is an example of using assertions for error handling.

05:42 If you execute this code in normal mode, the assertion will catch the negative number, as you may expect.

05:52 But if you execute this code in production with disabled assertions, then square() will never run the assert statement and raise an AssertionError.

06:05 In this situation, the tryexcept block is superfluous and nonfunctional. How can you fix this example? Updating square() to use an if statement and a ValueError.

06:26 Now square() deals with a condition by using an explicit if statement that can’t be disabled in production code. The tryexcept block now handles a ValueError, which is a more appropriate exception in this particular example.

06:56 You should never catch AssertionError exceptions in your code because that would silence failing assertions, which is a clear sign of them being misused.

07:05 Instead, catch concrete exceptions that are clearly related to the errors that you are handling and let your assertions fail. Use assertions only to check errors that shouldn’t happen during the normal execution of your programs unless you have a bug. Remember that assertions can be disabled.

07:24 In the next section of the course, you’ll take a look at more common pitfalls of using Python’s assert statement.

Become a Member to join the conversation.