
On 26 January 2016 at 14:26, Steven D'Aprano <steve@pearwood.info> wrote:
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
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. Paul