Assertions In Launchpad
Assertions are part of good programming practice, and they should be used in Launchpad code.
Although assertions are good, we shouldn't be using them just anywhere. These are the rules that we have to follow when using them in Launchpad:
- If the error is one that you'd expect clients of the code to handle, then it should be a checked exception rather than an assert, and be documented in the method or interface operation's docstring.
- If the error is one that clients of the code shouldn't handle (e.g. when preconditions are not met), then you should use an assert. In this case, there's two possible scenarios:
If you say something like "don't do such-and-such" in the docstring, then you should use an assert statement (recalling asserts will disappear if optimization is turned on so they should never be used to prevent bad behavior, such as returning the wrong value).
- Assertions should always have the conditional expression, and a string explaining the rationale. The rationale makes it easier to scan the OOPS report, for example.
No code should catch AssertionError: it is wrong for any code to catch AssertionError. So, if you want to highlight a programmer's error, and stop the execution of the program, then use an AssertionError.
As as example of how to use assertions, we have the method bugTasksWithSharedInterest() in PersonView, which is meant to be called only when we have a logged in user. This method is used only in one template, and protected by a tal:condition to make sure we have a logged in user. In this case, it's pretty fair to use an assertion, because calling this method without a logged in user is something that should not happen. This is the code:
def bugTasksWithSharedInterest(self): assert self.user is not None, 'This method should not be called without a logged in user'
Here is an example of an assertion that does not need one. In this case, we should be raising an error, instead.
def marryPersons(self, person1, person2): assert person1 is not None assert person2 is not None
It is interesting to note what Tim Peters thinks of assertions.
Testing your asserts
As with any other code, asserts should be documented and tested to make sure misbehaving programmers will be caught. But they shouldn't be in the general flow of documentation, because they're not part of the API. For this reason the test of asserts should be either in a separate file or in a separate section of the same file.