Clarity vs. code reuse/generality

Paul Rubin http
Sat Jul 4 14:29:20 EDT 2009


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.

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