status of Programming by Contract (PEP 316)?

Paul Rubin http
Fri Aug 31 01:07:47 EDT 2007


Robert Brown <bbrown at speakeasy.net> writes:
> In any case, I'm still not sure whether it would be useful to integrate DbC
> into Python.  

I guess I'm a little confused about what it would mean.  Suppose you
want to write a function that looks for a value using binary search
in a sorted list, n = bsearch(a,x).  The contract is:

  precondition: the input list a is sorted.
  postcondition: the output is an integer n, such that if
     x is an element of the list, then a[n] == x.  If x is not
     in the list, then n is -1.

This is a reasonable application of dbc since the precondition and
postcondition are easy to specify and check, but the binary search
algorithm is tricky enough to be susceptible to implementation errors.

The trouble is, the obvious way to write the precondition and
postcondition take linear time, while the binary search should take
log(n) time.  In the traditional unit test approach, that's ok, you'd
run the test as part of the build process but not each time the
function is actually called.  With something like SPARK/Ada (and maybe
Eiffel), you'd statically validate the conditions.  But in Python, the
check occurs at runtime unless you disable it, famously compared to
wearing your parachute on the ground but taking it off once your plane
is in the air.

I guess one difference from unit test philosophy is that at least
sometime, you'd run the entire application with all the dbc checks
enabled, and just live with the slowdown.



More information about the Python-list mailing list