PyContracts is a Python package that allows to declare constraints on function parameters and return values. It supports a basic type system, variables binding, arithmetic constraints, and has several specialized contracts (notably for Numpy arrays).
I have recently released version 1.6, which, along with various bugfixes, introduces the
ContractsMeta is a drop-in replacement for ABCMeta that allows you to declare contracts for a superclass and then have those contracts automatically enforced for any class that derives from it.
For example, let us define a “timer” interface whose start method requires a positive number:
from contracts import ContractsMeta, contract from abc import abstractmethod class TimerInterface(): __metaclass__ = ContractsMeta @abstractmethod @contract(interval='(float|int),>0') def start(self, interval): pass
Now we can subclass TimerInterface:
class Timer(TimerInterface): def start(self, interval): time.sleep()
and all contracts will be automatically inherited:
t = Timer() t.start(-1) # raises ContractNotRespected
In this case, this is the raised Exception:
contracts.interface.ContractNotRespected: Breach for argument 'interval' to Timer:start(). Condition -1 >= 0 not respected checking: >=0 for value: Instance of int: -1 checking: (float|int),>=0 for value: Instance of int: -1