Paul Rubin wrote:
kj <no.em...@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.

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to