PyContracts 1.6 adds ContractsMeta meta-class for inheriting contracts

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 metaclass.

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

    def start(self, interval):

Now we can subclass TimerInterface:

class Timer(TimerInterface):

    def start(self, interval):

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