[Python-ideas] DBC (Re: Explicit variable capture list)

Andrew Barnert abarnert at yahoo.com
Mon Jan 25 19:42:59 EST 2016


On Jan 25, 2016, at 15:34, Steven D'Aprano <steve at pearwood.info> wrote:
> 
> Okay, just to satisfy your curiosity, and not as a concrete proposal at 
> this time, here is a sketch of the sort of thing Eiffel uses for Design 
> By Contract.

I think it's worth explaining why this has to be an actual language feature, not something you just do by writing functions named "requires" and "ensures". Many of the benefits you cited would work just fine with a PyPI-library solution, but there are some problems that are much harder to solve:

* You usually want requires to be able to access the return value and exception state, and maybe even any locals, and ensure to be able to access the parameters.

* Faking ensure usually means finally or with (which means indenting your entire function) or a wrapper function (while precludes many simple designs).

* Many contract assertions are slow (or even dangerous, when not upheld) to calculate, so just no-opping out the checker functions doesn't help.

* Class invariants should be automatically verified as ensures on all public methods except __del__ and (if it raises) __init__.

* Subclasses that override a method need to automatically inherit the base class's pre- and post-conditions (as well as possibly adding some of their own), even if they don't call the super method.

* Some contract assertions can be tested at compile time. (Eiffel doesn't have much experimentation here; C# does, and there are rumors about Swift with clang-static-analyzer.)

Some of these things can be shoehorned in with frame hacks and metaclasses and so on, but it's not fun. There's a lot of history of people trying to fake it in other languages and then giving up and saying "just use comments until we can build it into language version n+1". (See D 1.0, Core C++ Standard for C++14/17, C# 4, Swift 2...) There have been a few attempts for Python, but most of them seem to have run into similar problems, after a lot of messing around with metaclasses and so on.



More information about the Python-ideas mailing list