ANN: Design By Contract for Python 1.0 beta 1

Terence Way terry at wayforward.net
Thu May 29 09:41:39 EDT 2003


On Thu, 29 May 2003 08:50:17 -0400, Dickon Reed wrote:

>> import types
> class A:
>     """
>     inv:
>       isinstance(self.x, types.StringTypes)
>     """
>     def __init__(self, x):
>         """
>         pre:
>           isinstance(x, self.StringTypes)

That needs to be 'isinstance(x, types.StringTypes)

This is what's happening:  I ignore invariants on entry to __init__
like you suggest.  But I check invariants after a function completes,
even if it raises an exception.  The exception being raised here is
AttributeError, instance A doesn't have attribute 'StringTypes' which
I catch, then check the invariant, which fails.

Cool.

I must fix: my constructor call mustn't check invariants on exceptions.

> Also, the backtrace showing the File "<string>" but not showing the
> actual code that caused the exception is a bit unfortunate. I can hack
> around that for the case where the assertion fails (by modifiying
> contract.py to give the assertion a parameter containing the contract
> string ), but I'm not sure how to do this for other exceptions generated
> by that code.

Okay, I'll spend some time with that.  I know 'doctest' manages to
do a good job showing actual code.  I'll plunder from there.

> Again, keep up the good work, and I (think I) would love to see
> something like this in the standard library, and maybe used quite
> heavily in the standard library modules. It seems to me DBC for a
> dynamically agile language is interesting; it means you get to declare
> exactly the constraints you want on the implementation, without simple
> static typing forcing you to write constraints which just reduce your
> polymorphism. You also get to add the contracts later, when tidying up
> code which you thought was throwaway but ended up being important.
> Distinguishing between regular assertion failures (i.e. implementation
> bugs) and precondition violations (i.e. usage bugs) seems a step
> forward, and not having to repeat invariant assertions throughout the
> methods in a class means that in practice they get checked more often.
> 
> Thanks,
> Dickon
 
Thanks a lot!




More information about the Python-list mailing list