[Python-ideas] Pre-conditions and post-conditions
Steven D'Aprano
steve at pearwood.info
Mon Aug 27 08:50:12 EDT 2018
On Mon, Aug 27, 2018 at 12:12:22PM +0100, Ivan Levkivskyi wrote:
> On Mon, 27 Aug 2018 at 11:39, Steven D'Aprano <steve at pearwood.info> wrote:
>
> > On Mon, Aug 27, 2018 at 09:24:20AM +0100, Ivan Levkivskyi wrote:
> > > TBH, I think one of the main points of design by contract is that
> > contracts
> > > are verified statically.
> >
> > No, that's not correct. Contracts may be verified statically if the
> > compiler is able to do so, but they are considered runtime checks.
> >
>
> Considered by whom? By people who prefer `assert isinstance(x, int)` over
> `x: int`? :-)
No, considered by Bertrand Meyer, the inventor of Design By Contract and
the programming language Eiffel.
Contracts are not limited to the things which static type-checkers are
capable of testing, but can and do involve checks which are impossible
or impractical to test at compile-time, like "today is Tuesday" or "the
account balance is greater than the amount you are trying to withdraw".
> Contract in 99% of cases is just another word for type (maybe a very
> complex type like `DAG[T] <: Graph[T]`).
> Everything else, like `x >= y` is better expressed as an explicit assert
> with an assert message.
Contracts ARE assertions. They are assertions about the input a method
expects, not merely the type but the value, what result it intends to
return, and the invariants of the class after the method is called. Like
assertions, they are called at runtime, and can be disabled.
Using contracts to enforce type-correctness wouild be silly in Eiffel,
because Eiffel already has a powerful static type system.
Sybtax-wise, if you're interested in what is possible in a Python-like
language, you could do worse than check out Cobra:
http://cobra-language.com/trac/cobra/wiki/Contracts
--
Steve
More information about the Python-ideas
mailing list