PyDBC provides a Python 2.2 metaclass which implements precondition, postcondition and invariant functionality.
PyDBC operates by rewriting method calls and variable accesses at module load time. Method calls are modified to call other methods representing pre/post conditions and class invariants, while varable accesses are modified to call a method representing class invariants.
There are a few great things about implementing these features using a rewriting metaclass:
Using PyDBC in your program is very easy:
foo__pre, foo__post and __invar are a precondition, a post condition and the
class invariant, respectively.
import dbc
__metaclass__ = dbc.DBC
class Foo:
def __invar(self):
assert isinstance(self.a, int)
def __init__(self, a):
self.a = a
def foo(self, a):
self.a *= a
def foo__pre(self, a):
assert a > 0
def foo__post(self, rval):
assert rval is None
Convinced yet? If not, take a look at this. Otherwise, head on over to the download page and grab the latest release.