[Python-ideas] Pre-conditions and post-conditions

Jonathan Fine jfine2358 at gmail.com
Sat Sep 8 15:34:36 EDT 2018


Michel Desmoulin wrote:

> Isn't the purpose of "assert" to be able to do design by contract ?
>
>     assert test, "error message is the test fail"
>
> I mean, you just write your test, dev get a feedback on problems, and
> prod can remove all assert using -o.
>
> What more do you need ?

Good question. My opinion is that assert statements are good. I like them.

But wait, more is possible. Here are some ideas.

1. Checking the return value (or exception). This is a post-condition.

2. Checking return value, knowing the input values. This is a more
sophisticated post-condition.

3. Adding checks around an untrusted function - possibly third party,
possibly written in C.

4. Selective turning on and off of checking.

The last two, selective checks around untrusted functions, I find
particularly interesting.

Suppose you have a solid, trusted, well-tested and reliable system.
And you add, or change, a function called wibble(). In this situation,
errors are most likely to be in wibble(), or in the interface to
wibble().

So which checks are most valuable? I suggest the answer is

1. Checks internal to wibble.

2. Pre-conditions and post-conditions for wibble

3. Pre-conditions for any function called by wibble.

Suppose wibble calls wobble. We should certainly have the system check
wobble's preconditions, in this situation. But we don't need wobble to
run checks all the time. Only when the immediate caller is wibble.

I think assertions and design-by-contract point in similar directions.
But design-by-contract takes you further, and is I suspect more
valuable when the system being built is large.

Thank you, Michel, for your good question.

-- 
Jonathan


More information about the Python-ideas mailing list