Documenting Your Code With Assertions
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.
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.
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.
Become a Member to join the conversation.