On Jul 9, 2009, at 10:57 PM, Steven D'Aprano wrote:

On Fri, 10 Jul 2009 03:28:04 +0100, Nobody wrote:

On Thu, 09 Jul 2009 04:57:15 -0300, Gabriel Genellina wrote:

Nobody says you shouldn't check your data. Only that "assert" is not
the right way to do that.

"assert" is not the right way to check your *inputs*. It's a perfectly reasonable way to check data which "should" be valid, as well as a way
to document what variables are supposed to contain.

Where are those variables coming from?

The distinction really boils down to this:

* asserts should never fail. If there is any chance that an assertion
might fail outside of test suites, then don't use assert.


You can't control what input the caller provides to a function, so unless
the data is generated inside the function, a caller might provide
something unexpected. Therefore, assert is inappropriate for checking
function parameters, even if that function is "private" and only called
by your own functions.

(1) So-called "private" or "internal" functions have a habit of becoming
public, and then you have asserts in public functions.

(2) If public() calls _private(x), and _private uses assert to check the
value of x, there is a risk that if public() is buggy and supplies an
invalid x, the assertion will never be checked and _private() will return
incorrect results.

(3) assert is absolutely unsuitable for enforcing pre-conditions and post- conditions, unless such conditions are mere "guidelines", because assert
can be switched off at runtime.


Unless, of course, you want to switch off such checking at runtime, as you might when using a design-by-contract approach.

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

Reply via email to