Just curious, Michael, what would you like the Python syntax version to look like if you *can* do whatever metaclass or stack hackery that's needed?  I'm a little confused when you mention a decorator and a context manager in the same sentence since those would seem like different approaches.  E.g.:

@Contract(pre=my_pre, post=my_post)
def my_fun(...): ...

Versus:

with contract(pre=my_pre, post=my_post):
    def my_fun(...): ...

Versus:

def my_fun(...):
    with contract(pre=my_pre, post=my_post):
        <suite>

I'm sure lots of other variations are possible too (if any can be made fully to work).


On Mon, Jan 25, 2016 at 5:01 PM, Michael Selik <mike@selik.org> wrote:
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.

_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/



--
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.