[Python-ideas] Simplicity of C (was why is design-by-contracts not widely)
Stephen J. Turnbull
turnbull.stephen.fw at u.tsukuba.ac.jp
Mon Oct 1 09:09:23 EDT 2018
> On Sun, Sep 30, 2018, 15:12 Stephen J. Turnbull <
> turnbull.stephen.fw at u.tsukuba.ac.jp> wrote:
> > What does "inherited" mean? Just that methods that are not overridden
> > retain their contracts?
> Contracts are attached to interfaces, not to specifications. So
> when you have abstract base class, it defines contracts, and
> implementing classes must adhere to these contracts - the can only
> strengthen it, not weaken it.
Stated in words, it sounds very reasonable.
Thinking about the implications for writing Python code, it sounds
very constraining in the context of duck-typing. Or, to give a
contrapositive example, you can write few, if any, contracts for
dunders beyond their signatures. For example, len(x) + len(y) ==
len(x + y) is not an invariant over the classes that define __len__
(eg, set and dict, taking the "x + y" loosely for them). Of course if
you restrict to Sequence, you can impose that invariant. The question
is the balance.
It sounds to me like the proof of the pudding for Python will be
annotating the ABC module with contracts. If that turns out to be a
mostly fruitless exercise, it's hard to see how "real" contracts
(vs. using asserts to "program in contracting style") are an important
feature for Python in general.
That said, given the passion of the proponents, if we can come up with
an attractive style for implementing contracts without a language
change, I'd be +0 at least for adding a module to the stdlib. But
this is a Python 3.9 project, given the state of the art.
> This is precisely like with types, since types are contracts (and
> vice versa, in a way).
Not Python types (== classes), though. As a constraint on behavior,
subclassing is purely nominal, although Python deliberately makes it
tedious to turn a subclass of str into a clone of int.
More information about the Python-ideas