On Mon, Jan 25, 2016 at 6:43 PM Andrew Barnert via Python-ideas <python-ideas@python.org> wrote:
On Jan 25, 2016, at 15:34, Steven D'Aprano <steve@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:

Some of these things can be shoehorned in with frame hacks and metaclasses and so on, but it's not fun. ... 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.

As you were writing this, I was sketching out an implementation using a callable FunctionWithContract context manager as a decorator. As you say, the trouble seems to be elegantly capturing the function output and passing that to an ensure or __exit__ method. The requires side isn't so bad.

Still, I'm somewhat hopeful that someone more skilled than I might be able to write an elegant ``Contract`` type using current Python syntax.