Contracts for Python

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.

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*.

        # must be a list
        isinstance(a, list)

        # all elements must be comparable with all other items
               lambda i: forall(range(len(a)),
                                lambda j: (a[i] < a[j]) ^ (a[i] >= a[j])))

        # 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.