Documenting Your Code With Assertions
00:00
Documenting Your Code With Assertions. The assert
statement is an effective way to document your code. For example, if you want to state that a specific condition
should always be true in your code, then using an assertion can be better and more effective than a comment or a docstring.
00:20 To understand why assertions can be a handy documenting tool, let’s say you have a function that takes a server name and a tuple of port numbers. The function will iterate over the port numbers trying to connect to the target server. For your function to work correctly, the tuple of ports should not be empty.
00:53
If someone accidentally calls get_response()
with an empty tuple, then the for
loop will never run, and the function will return None
even if the server is available to alert programmers to this buggy call, you can use a comment, as you did in the example on-screen.
01:21
However, using an assert
statement can be more effective.
01:37
The advantage of an assert
statement over a comment is that when the condition isn’t true, assert
immediately raises an AssertionError
.
02:03 After that, the code stops running, so it avoids abnormal behaviors and points you directly to the specific problem. Using assertions in situations like this is an effective and powerful way to document your intentions and avoid hard-to-find bugs due to accidental errors or malicious actors. In the next section of the course, you’ll increase your knowledge of assertions by looking at their use for debugging.
Bartosz Zaczyński RP Team on May 30, 2023
@John Rutledge What you’re looking at is the traceback pointing to the exact line of the code and an expression within that line that caused the exception. When you look further down, you’ll see the formatted message with the actual value for the ports
variable:
AssertionError: ports expected a non-empty tuple, got()
John Rutledge on June 1, 2023
Thank you, Bartosz! I get it now.
Become a Member to join the conversation.
John Rutledge on May 30, 2023
At 2:03 in “Documenting Your Code With Assertions”, the assertion error message shown in the REPL prints out the f-string literal f”ports expected a non-empty tuple, got{ports}”
Should it not print out the formatted string?