assertions to validate function parameters

Carl Banks pavlovevidence at gmail.com
Sat Jan 27 15:19:59 CET 2007



On Jan 25, 11:26 pm, Steven D'Aprano 
<s... at REMOVE.THIS.cybersource.com.au> wrote:
> Note also that for real code, a bare assert like that is uselessly
> uninformative:
>
> >>> x = 1
> >>> assert x == 3Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AssertionError

In real code, a traceback usually prints the line of code containing 
the failed assertion.


> This is better:
>
> >>> assert x == 3, "x must be equal to three but is %s instead" % xTraceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AssertionError: x must be equal to three but is 1 instead
>
> This is even better still:
>
> >>> if x != 3:...     raise ValueError("x must be equal to three but is %s instead" % x)
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ValueError: x must be equal to three but is 1 instead

These are are verbose to the point of silliness, and usually not worth 
the effort since assertions are only supposed to check for ostensibly 
impossible conditions.  Thus it shouldn't pop up often enough to 
justify writing a verbose error message in advance, and when it does 
trigger you're going to have to print the failed result in a debuging 
run anyways.


Carl Banks




More information about the Python-list mailing list