API
require
- class icontract.require[source]
Decorate a function with a precondition.
The arguments of the precondition are expected to be a subset of the arguments of the wrapped function.
- __init__(condition: ~typing.Callable[[...], ~typing.Any], description: ~typing.Optional[str] = None, a_repr: ~reprlib.Repr = <reprlib.Repr object>, enabled: bool = True, error: ~typing.Optional[~typing.Union[~typing.Callable[[...], ~icontract._globals.ExceptionT], ~typing.Type[~icontract._globals.ExceptionT], BaseException]] = None) None[source]
Initialize.
- Parameters:
condition –
precondition predicate
If the condition returns a coroutine, you must specify the error as coroutines have side effects and can not be recomputed.
description – textual description of the precondition
a_repr – representation instance that defines how the values are represented
enabled –
The decorator is applied only if this argument is set.
Otherwise, the condition check is disabled and there is no run-time overhead.
The default is to always check the condition unless the interpreter runs in optimized mode (
-Oor-OO).error –
The error is expected to denote either:
A callable.
erroris expected to accept a subset of function arguments and return an exception. Theerroris called on contract violation and the resulting exception is raised.A subclass of
BaseExceptionwhich is instantiated with the violation message and raised on contract violation.An instance of
BaseExceptionthat will be raised with the traceback on contract violation.
- __call__(func: CallableT) CallableT[source]
Add the precondition to the list of preconditions of the function
func.The function
funcis decorated with a contract checker if there is no contract checker in the decorator stack.- Parameters:
func – function to be wrapped
- Returns:
contract checker around
funcif no contract checker on the decorator stack, orfuncotherwise
snapshot
- class icontract.snapshot[source]
Decorate a function with a snapshot of argument values captured prior to the function invocation.
A snapshot is defined by a capture function (usually a lambda) that accepts one or more arguments of the function. If the name of the snapshot is not given, the capture function must have a single argument and the name is equal to the name of that single argument.
The captured values are supplied to postconditions with the OLD argument of the condition and error function. Snapshots are inherited from the base classes and must not have conflicting names in the class hierarchy.
- __init__(capture: Callable[[...], Any], name: Optional[str] = None, enabled: bool = True) None[source]
Initialize.
- Parameters:
capture – function to capture the snapshot accepting a one or more arguments of the original function prior to the execution
name – name of the snapshot; if omitted, the name corresponds to the name of the input argument
enabled –
The decorator is applied only if
enabledis set.Otherwise, the snapshot is disabled and there is no run-time overhead.
The default is to always capture the snapshot unless the interpreter runs in optimized mode (
-Oor-OO).
- __call__(func: CallableT) CallableT[source]
Add the snapshot to the list of snapshots of the function
func.The function
funcis expected to be decorated with at least one postcondition before the snapshot.- Parameters:
func – function whose arguments we need to snapshot
- Returns:
funcas given in the input
ensure
- class icontract.ensure[source]
Decorate a function with a postcondition.
The arguments of the postcondition are expected to be a subset of the arguments of the wrapped function. Additionally, the argument “result” is reserved for the result of the wrapped function. The wrapped function must not have “result” among its arguments.
- __init__(condition: ~typing.Callable[[...], ~typing.Any], description: ~typing.Optional[str] = None, a_repr: ~reprlib.Repr = <reprlib.Repr object>, enabled: bool = True, error: ~typing.Optional[~typing.Union[~typing.Callable[[...], ~icontract._globals.ExceptionT], ~typing.Type[~icontract._globals.ExceptionT], BaseException]] = None) None[source]
Initialize.
- Parameters:
condition –
postcondition predicate.
If the condition returns a coroutine, you must specify the error as coroutines have side effects and can not be recomputed.
description – textual description of the postcondition
a_repr – representation instance that defines how the values are represented
enabled –
The decorator is applied only if this argument is set.
Otherwise, the condition check is disabled and there is no run-time overhead.
The default is to always check the condition unless the interpreter runs in optimized mode (
-Oor-OO).error –
The error is expected to denote either:
A callable.
erroris expected to accept a subset of function arguments and return an exception. Theerroris called on contract violation and the resulting exception is raised.A subclass of
BaseExceptionwhich is instantiated with the violation message and raised on contract violation.An instance of
BaseExceptionthat will be raised with the traceback on contract violation.
- __call__(func: CallableT) CallableT[source]
Add the postcondition to the list of postconditions of the function
func.The function
funcis decorated with a contract checker if there is no contract checker in the decorator stack.- Parameters:
func – function to be wrapped
- Returns:
contract checker around
funcif no contract checker on the decorator stack, orfuncotherwise
invariant
- class icontract.invariant[source]
Represent a class decorator to establish the invariant on all the public methods.
Class method as well as “private” (prefix
__) and “protected” methods (prefix_) may violate the invariant. Note that all magic methods (prefix__and suffix__) are considered public and hence also need to establish the invariant. To avoid endless loops when generating the error message on an invariant breach, the method__repr__is deliberately exempt from observing the invariant.The invariant is checked before and after the method invocation.
As invariants need to wrap dunder methods, including
__init__, their conditions can not be async, as most dunder methods need to be synchronous methods, and wrapping them with async code would break that constraint.For efficiency reasons, we do not check the invariants at the calls to
__setattr__and__getattr__methods by default. If you indeed want to check the invariants in those calls as well, make sure to adapt the argumentcheck_onaccordingly.- __init__(condition: ~typing.Callable[[...], ~typing.Any], description: ~typing.Optional[str] = None, a_repr: ~reprlib.Repr = <reprlib.Repr object>, enabled: bool = True, error: ~typing.Optional[~typing.Union[~typing.Callable[[...], ~icontract._globals.ExceptionT], ~typing.Type[~icontract._globals.ExceptionT], BaseException]] = None, check_on: ~icontract._types.InvariantCheckEvent = InvariantCheckEvent.CALL) None[source]
Initialize a class decorator to establish the invariant on all the public methods.
- Parameters:
condition –
invariant predicate.
The condition must not be a coroutine function as dunder functions (including
__init__) of a class can not be async.description – textual description of the invariant
a_repr – representation instance that defines how the values are represented
enabled –
The decorator is applied only if this argument is set.
Otherwise, the condition check is disabled and there is no run-time overhead.
The default is to always check the condition unless the interpreter runs in optimized mode (
-Oor-OO).error –
The error is expected to denote either:
A callable.
erroris expected to accept a subset of function arguments and return an exception. Theerroris called on contract violation and the resulting exception is raised.A subclass of
BaseExceptionwhich is instantiated with the violation message and raised on contract violation.An instance of
BaseExceptionthat will be raised with the traceback on contract violation.
check_on –
Specify when to check the invariant.
If
InvariantCheckEvent.CALLis set, the invariant will be checked on all the method calls except__setattr__.If
InvariantCheckEvent.SETATTRis set, the invariant will be checked on__setattr__calls.
- Returns:
- __call__(cls: ClassT) ClassT[source]
Decorate each of the public methods with the invariant.
Go through the decorator stack of each function and search for a contract checker. If there is one, add the invariant to the checker’s invariants. If there is no checker in the stack, wrap the function with a contract checker.
DBCMeta
- class icontract.DBCMeta(name, bases, namespace, **kwargs)[source]
Define a meta class that allows inheritance of the contracts.
The preconditions are weakened (“require else”), while postconditions (“ensure then”) and invariants are strengthened according to the inheritance rules of the design-by-contract.
DBC
ViolationError
InvariantCheckEvent
- class icontract.InvariantCheckEvent(value)[source]
Define when an invariant should be checked.
Attributes:
Evaluate the invariant before and after all calls to a method.
Evaluate the invariant before and after all the calls to
__setattr__.Always evaluate the invariant, *i.e., both on calls and on attributes set.
- CALL = 1
Evaluate the invariant before and after all calls to a method.
- SETATTR = 2
Evaluate the invariant before and after all the calls to
__setattr__.