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

Steven D'Aprano steve at pearwood.info
Mon Aug 27 06:23:08 EDT 2018


On Mon, Aug 27, 2018 at 09:04:21AM +0200, Jacco van Dorp wrote:
> Total noob speaking here, but....
> 
> Those contracts are mostly important during development right ?

That assumes that production code is free of bugs.

Usual practice in the Eiffel world is, I believe, to disable post- 
condition checking and other assertions in production code, but leave 
pre-condition checks in place.

Note: for those unfamiliar with Design By Contract, pre- and post- 
condition checks and assertions are NOT used to detect predictable error 
states, such as bad user input or IO errors. They are only used for 
testing program correctness. A failed contract or assertion can only 
mean a bug in the program. In a totally bug-free program contracts can 
safely be disabled.


> Slowdown isn't that much of an issue during development.

For many cases, it isn't an issue during production either.


> So you could make a debug
> mode that enforces the contracts, and a production mode that code 
> users can use during production to stop the slowdown

In Eiffel, contracts can be disabled or enable globally, or on a 
class-by-class basis.


> - in this case, your decorators
> can return their functions/classes unaltered. If they do end up with
> problems, you can always ask them to run the same inputs with debug mode on
> to see where it goes wrong.
> 
> For the rest, i'm totally new to design by contract. I do get the draw of
> it, but im not sure if I'd ever really use it. I tend to solve my problems
> with a royal sprinkling of logger.debug(f"{val_i_need_to_check}").

The differences between design by contract and sprinkling messages in 
the log include:

- the compiler (or interpreter) never forgets to read the logs 
  looking for failures;

- when a failure occurs, the program halts, so you know its broken,
  rather than silently continuing and perhaps doing something 
  unexpected;

- you don't need to read the logs and try to remember why it is
  that you're printing the value of ``foo`` and whether its a
  good thing or a bad thing that it has the value you're seeing.


Here's an introduction to design by contract:

https://www.eiffel.org/doc/eiffel/ET-_Design_by_Contract_%28tm%29%2C_Assertions_and_Exceptions



-- 
Steve


More information about the Python-ideas mailing list