Programming by Contract allows a programmer to document a function/class with statements describing behavior.
The most famous use/example of contracts is in the language Eiffel — a good introduction to programming contracts has been written by the people who wrote Eiffel.
Source Package (includes everything listed below) | contract-1.4.tar.gz 23Kb; 1.4; August 31, 2007 |
Draft Python Enhancement Proposal (PEP) | pep-0316.html |
Reference Implementation | contract.py |
Examples | sort.py |
circbuf.py | |
Earlier versions: | contract-1.3.tar.gz 23Kb; 1.3; June 02, 2007 |
contract-1.1.tar.gz 28Kb; 1.1; October 19, 2005 |
|
contract-1.0b3.tar.gz 27Kb; 1.0 beta 3; June 21, 2003 |
|
contract-1.0b2.tar.gz 24Kb; 1.0 beta 2; June 6, 2003 |
|
contract-1.0b1.tar.gz 19Kb; 1.0 beta 1; May 21, 2003 |
I believe this makes a good addition to the Python language, taking all the good features of Eiffel's contracts and making them, well, Pythonic. As an example, let's look at the contract for a sort function:
def sort(a): """Sort a list *IN PLACE*. pre: # must be a list isinstance(a, list) # all elements must be comparable with all other items forall(range(len(a)), lambda i: forall(range(len(a)), lambda j: (a[i] < a[j]) ^ (a[i] >= a[j]))) post[a]: # length of array is unchanged len(a) == len(__old__.a) # all elements given are still in the array forall(__old__.a, lambda e: __old__.a.count(e) == a.count(e)) # the array is sorted forall([a[i] >= a[i-1] for i in range(1, len(a))]) """ |
This tells us everything we need to know about sort. During debugging, these statements are actually executed. If any of the pre-conditions are false, an exception is raised so the caller can be debugged. If any of the post-conditions are false, a similar exception is raised so the sort function can be debugged.