ANN: Design By Contract for Python 1.0 beta 1

Dickon Reed dickonr at chiark.greenend.org.uk
Thu May 29 12:29:51 EDT 2003


In article <bb52ji$ke3$1 at slb6.atl.mindspring.net>,
Terence Way  <terry at wayforward.net> wrote:
>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.

They say the double failures are the ones that always get you :-)

Thanks for the analysis, I can go on with wildly adding contracts to the 7000
line python package I'm working on. 

I'm curious whether this will help especially as "I'm not signing that
contract yet" at:

http://www.hole.fi/jajvirta/weblog/20030528T2101.html

I've already spotted three internal inconsistencies by adding a dozen
class invariants over a couple of classes, and they are the kind of thing
that might not have been noticed for a while until they manifest as bugs, 
so I'm already happy.

Dickon





More information about the Python-list mailing list