Clarity vs. code reuse/generality

MRAB python at mrabarnett.plus.com
Sat Jul 4 20:43:24 CEST 2009


Paul Rubin wrote:
> kj <no.email at please.post> writes:
>> This implies that code that uses *any* assert statement (other than
>> perhaps the trivial and meaningless ones like "assert True") is
>> liable to break, because whatever it is that these assert statements
>> are checking "on some occasions, ... would go unchecked, potentially
>> breaking your code."
> 
> Yes, that implication is absolutely valid.  The purpose of assert
> statements is to debug the code, by checking for conditions that are
> supposed to be impossible.  Unless the program is broken (i.e.  the
> impossible happened), no assert statement should ever trigger.
> 
Technically these are known as "invariants". An assertion will always be
True if the program is bug-free, no matter what the user might throw at
it; it's not the same as validation.

> Invalid input data is not considered impossible and doesn't imply a
> broken program, so assert statements are not the appropriate way to
> check for it.  I like to use a function like
> 
>   def check(condition, msg="data error"):
>      if not condition: raise ValueError, msg
> 
>   ... 
>   check (x >= 0, "invalid x")  # raises ValueError if x is negative
>   y = sqrt(x)
> 
> instead.




More information about the Python-list mailing list