Understanding Common Pitfalls
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.
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.
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.
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.
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
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.
square() deals with a condition by using an explicit
if statement that can’t be disabled in production code. The
except block now handles a
ValueError, which is a more appropriate exception in this particular example.
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.
Become a Member to join the conversation.