Avoiding More Pitfalls
In this section of the course, you’ll see some more common pitfalls when using Python’s
assert statement. Another subtle pitfall with the
assert statement appears when you use this statement to check operations, functions, or expressions that have some kind of side effect. In other words, these operations modify the state of objects outside the operation’s scope.
Using assertions to make sure that your function is returning the correct item can seem appropriate. However, this will cause the function’s internal side effect to run in every assertion, modifying the original content of
01:36 Too many assertions in production can impact your code’s performance. This issue becomes critical when the asserted conditions involve too much logic, such as long compound conditions, long-running predicate functions, and classes implying a costly instantiation process.
Assertions can impact your code’s performance in two main ways. They will take time to execute and use extra memory. An
assert statement that checks for a
None value can be relatively inexpensive.
02:31 Either strategy will optimize your code by generating an assertions-free compiled bytecode, which will run more quickly and take up less memory. Additionally, to prevent performance issues during development, your assertions should be fairly slim and to the point.
02:57 This behavior makes sense because you typically develop, debug, and test your code in normal mode. If you want to disable assertions in Python, then it needs to be done explicitly. In contrast, other programming languages have assertions disabled by default. For example, if you’re coming into Python from Java, you may assume that assertions won’t run unless you explicitly turn them on.
Become a Member to join the conversation.