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

Steven D'Aprano steve at pearwood.info
Tue Jan 26 09:26:47 EST 2016


On Mon, Jan 25, 2016 at 05:24:29PM -0800, David Mertz wrote:
> 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.:

I'm not Michael, but since I started this discussion, I'll give an 
answer.

I haven't got any working code, but I think something like this would be 
acceptable as a proof-of-concept. I'd use a class as a fake namespace, 
with either a decorator or metaclass:

class myfunction(metaclass=DBC):
    def myfunction(args):
        # function implementation
        ...
    def requires():
        ...
    def ensures():
        ...


The duplication of the name is a bit ugly, and it looks a bit funny for 
the decorator/metaclass to take a class as input and return a function, 
but we don't really have anything else that makes a good namespace. 
There's functions themselves, of course, but it's hard to get at the 
internals.

The point is to avoid having to pre-define the pre- and post-condition 
functions. We don't write this:

def __init__(self): 
    ...
def method(self, arg): 
    ...

class MyClass(init=__init__, method=method)


and nor should we have to do the same for require/ensure.


-- 
Steve


More information about the Python-ideas mailing list