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 assert Statements

00:00 Understanding Python’s assert Statements. You now know what assertions are, what they’re good for, and when you shouldn’t use them in your code.

00:10 It’s time to learn the basics of writing your own assertions. First, note that Python implements assertions as a statement with the assert keyword rather than as a function.

00:21 This behavior can be a common source of confusion and issues, as you’ll learn later on. An assert statement consists of the assert keyword, the expressional condition to test, and an optional message.

00:34 The condition is always supposed to be true. If the assertion condition is true, then nothing happens, and the program continues its normal execution. On the other hand, if the condition becomes false, then assert halts the program by raising an AssertionError.

00:51 In Python, assert is a simple statement with a syntax seen on-screen. Here, expression can be any valid Python expression or object, which is then tested for truthiness. If expression is false, then the statement throws an AssertionError.

01:06 The assertion_message parameter is optional but encouraged. It can hold a string describing the issue that the statement is supposed to catch. Here’s how the statement works in practice.

01:24 With a truthy expression, the assertion succeeds, and nothing happens. In that case, the program continues its normal execution.

01:38 In contrast, a falsey expression makes the assertion fail, raising an AssertionError and breaking the program’s execution.

01:49 To make your assert statements clear to other developers, you should add a descriptive assertion message.

01:59 The message in this assertion clearly states which condition should be true and what is making the condition fail.

02:09 Note that the assertion_message argument to assert is optional. However, it can help you better understand the condition under test and figure out the problem that you are facing. So whenever you use assert, it’s a good idea to use a descriptive assertion message for the traceback of the AssertionError exception.

02:29 An important point regarding the assert syntax is the statement does not require a pair of parentheses to group the expression and the optional message. In Python, assert is a statement, not a function.

02:41 Using a pair of parentheses can lead to unexpected behaviors. For example, an assertion such as the one seen on-screen will raise a SyntaxWarning.

02:56 This warning has to do with non-empty tuples always being truthy in Python. In this example, the parentheses turn the assertion expression and message into a two-item tuple, which always evaluates to true. Fortunately, recent versions of Python throw a SyntaxWarning to alert you of this. However, in older versions of the language, an assert statement as seen on-screen will always succeed.

03:24 This issue often appears when you’re using long expressions or messages that take more than a single line. In these cases, the parentheses are the natural way to format the code, and you may end up with something like the code seen on-screen.

03:38 Using a pair of parentheses to split a long line into multiple lines is a common formatting practice in Python code. However, in the context of an assert statement, the parentheses turn the assertion expression and the message into a two-item tuple. In practice, if you want to split a long assertion into several lines, then you can use the backslash character (\) for explicit line joining. The backslash at the end of the first line of this assertion joins the two physical lines into a single logical line. This way, you can have an appropriate line length without the risk of a warning or a logical error in your code.

04:18 Pep 679 was created in January 2022 and is proposing to allow parentheses around the assertion expression message. If the PEP gets approved and implemented, then the issue of accidental tuples won’t affect Python code in the future.

04:34 There is an edge case of this parentheses-related issue. If you provide only the assertion expression in parentheses, then assert will work just fine.

04:53 Why is this happening? To create a single-item tuple, you need to place a comma after the item itself. In the code on-screen, the parentheses by themselves don’t create a tuple, and that’s why the interpreter ignores the parentheses, and assert works as expected. Even though the parentheses work in this scenario, it’s not a recommended practice. You can end up shooting yourself in the foot.

05:21 If the condition of an assert statement evaluates to false, then assert raises an AssertionError. If you provide the optional assertion message, then this message is internally used as an argument to the AssertionError class. Either way, the raised exception breaks your program’s execution.

05:38 Most of the time, you won’t raise AssertionError exceptions explicitly in your code. The assert statement takes care of raising this exception when the assertion condition fails. Additionally, as you’ll learn later on, you shouldn’t attempt to handle errors by writing code that catches the AssertionError. Finally, AssertionError is a built-in exception that inherits from the Exception class and is considered a concrete exception that should be raised instead of subclassed.

06:05 Now you know the basics of the assert statement. You’ve learned the statement syntax, how it works in practice, and also what the main characteristics of the AssertionError exception are.

06:17 It’s time to move forward and explore some effective and common ways to write assertions in Python, and that’s what you’ll be looking at in the next section of the course.

Become a Member to join the conversation.