You could define private (underscored) methods which will remain undecorated, so that _verify_less_than_equal
can call the undecorated functions. The for-loop
then can add the public API (methods without underscores) which are decorated versions of the private methods:
import types
def add_decorators(cls):
def decorate(fn):
def wrapped(self, x, y):
res = fn(self, x, y)
if not res:
raise ValueError('Verification failed! {}({}, {}) is False'
.format(fn.__name__, x, y))
return res
return wrapped
for k, v in vars(cls).items():
if isinstance(v, types.FunctionType):
if k.startswith('__'): continue
if k.startswith('_'):
setattr(cls, k[1:], decorate(v))
return cls
@add_decorators
class NeedsDecoration():
def _verify_less_than(self, x, y):
return x < y
def _verify_equal(self, x, y):
return x == y
def _verify_less_than_equal(self, x, y):
return self._verify_less_than(x, y) or self._verify_equal(x, y)
def __init__(self): pass
verifier = NeedsDecoration()
assert verifier.verify_less_than_equal(5, 5)
As desired, the last line does not raise an exception.