[Python-ideas] DBC (Re: Explicit variable capture list)
Chris Angelico
rosuav at gmail.com
Tue Jan 26 10:24:52 EST 2016
On Wed, Jan 27, 2016 at 2:06 AM, Paul Moore <p.f.moore at gmail.com> wrote:
> Well, classes can be callable already, so how about
>
> @DBC
> class myfunction:
> def __call__(self, args):
> ...
> @precondition
> def requires(self):
> ...
> @postcondition
> def ensures(self, result):
> ...
>
> The DBC class decorator does something like
>
> def DBC(cls):
> def wrapper(*args, **kw):
> fn = cls()
> fn.args = args
> fn.kw = kw
> for pre in fn.__preconditions__:
> pre()
> result = fn(*args, **kw)
> for post in fn.__postconditions__:
> post(result)
> return wrapper
>
> Pre and post conditions can access the args via self.args and self.kw.
> The method decorators would let you have multiple pre- and
> post-conditions. Or you could use "magic" names and omit the
> decorators.
I'd rather use magic names - something like:
@DBC
class myfunction:
def body(self, args):
...
def requires(self):
...
def ensures(self, result):
...
and then the DBC decorator can create a __call__ method. This still
has one nasty problem though: the requires and ensures functions can't
see function arguments. You could get around this by duplicating the
argument list onto the other two, but who wants to do that?
ChrisA
More information about the Python-ideas
mailing list