Design by Contract for Python

Terence Way terry at wayforward.net
Wed May 14 15:38:30 EDT 2003


Excellent points.

Daniel Arbuckle's PyDBC 0.2 has a few minor problems, and one
major one.  Minor problems: no support for functions or modules;
contract checking functions should perhaps be private; and no
support for inheritance.  All this can be fixed quite easily.
Including the checking functions in the documentation would
require simple updates to pydoc, etc.

The major problem is support for 'old' variables.  Post-conditions
should be able to compare changed values with saved values.
I see no elegant way to do this with Daniel's approach.  To do
this with functions should require something ick, like so:

     def foo(self, a, b):
          blah, blah, blah

     def foo_pre(self, a, b):
          assert a > 5

     def foo_save(self, a, b):
         return [copy.copy(b)]

     def foo_post(self, old, ret, a, b):
         assert b == old[0] + 1


I think a compromise approach might work: for a function foo,
simply check if the functions _foo_pre and _foo_post are defined
and have matching arguments ( _foo_post would have to take
two additional arguments after the self argument).  If so, these
functions are executed as well...  ANDed with the documented
checks.

This solves several problems with *my* stuff: the largest being
access to closure variables (inaccessible by dynamically
generated checking functions, but accessible by the _foo_*
methods).

On Wednesday, May 14, 2003, at 12:47  PM, Michael Chermside wrote:

> Terence:
    ...
> However, I'm not sure that what you describe in your draft PEP is
> quite the way to go. In particular, I am very wary of stuffing code
> into doc comments. I think of preconditions, postconditions, and
> invariants as bits of code, which should be syntax checked just like
> any other, and colorized by the editor just like any other, they're
> just not EXECUTED like any other (ie, not at all in production mode).
>
> So I guess I'd prefer Daniel Arbuckle's approach to the use of doc
> comments.
>
> -- Michael Chermside
>






More information about the Python-list mailing list