contracts Package

contracts Package

class contracts.ContractsMeta(clsname, bases, clsdict)

Bases: abc.ABCMeta

This metaclass lets the subclasses inherit the specifications. Very useful for abstract commands.

contracts.contract(*args, **kwargs)[source]

Decorator for adding contracts to functions.

It is smart enough to support functions with variable number of arguments and keyword arguments.

There are three ways to specify the contracts. In order of precedence:

  • As arguments to this decorator. For example:

    @contract(a='int,>0',b='list[N],N>0',returns='list[N]')
    def my_function(a, b):
        # ...
        pass
    
  • As annotations (supported only in Python 3):

    @contract
    def my_function(a:'int,>0', b:'list[N],N>0') -> 'list[N]':
        # ...
        pass
    
  • Using :type: and :rtype: tags in the function’s docstring:

    @contract
    def my_function(a, b):
    
contracts.new_contract(*args)[source]

Defines a new contract type. Used both as a decorator and as a function.

1) Use as a function. The first parameter must be a string. The second parameter can be either a string or a callable function.

new_contract('new_contract_name', 'list[N]')
new_contract('new_contract_name', lambda x: isinstance(x, list) )
  • If it is a string, it is interpreted as contract expression; the given identifier will become an alias for that expression.

  • If it is a callable, it must accept one parameter, and either:

    • return True or None, to signify it accepts.
    • return False or raise ValueError or AssertionError, to signify it doesn’t.

    If ValueError is raised, its message is used in the error.

2) Use as a decorator.

Or, it can be used as a decorator (without arguments). The function name is used as the identifier.

@new_contract
def new_contract_name(x):
    return isinstance(x, list)

This function returns a Contract object. It might be useful to check right away if the declaration is what you meant, using Contract.check() and Contract.fail().

Parameters:
  • identifier (str) – The identifier must be a string not already in use (you cannot redefine list, tuple, etc.).
  • condition (type|callable|str) – Definition of the new contract.
Returns:

The equivalent contract – might be useful for debugging.

Return type:

Contract

backported Module

class contracts.backported.FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)

Bases: tuple

annotations

Alias for field number 6

args

Alias for field number 0

defaults

Alias for field number 3

kwonlyargs

Alias for field number 4

kwonlydefaults

Alias for field number 5

varargs

Alias for field number 1

varkw

Alias for field number 2

contracts.backported.getargspec(function)[source]
contracts.backported.getfullargspec(function)[source]

docstring_parsing Module

class contracts.docstring_parsing.Arg(desc=None, type=None)[source]

Bases: object

class contracts.docstring_parsing.DocStringInfo(docstring=None, params=None, returns=None)[source]

Bases: object

static parse(docstring)[source]
contracts.docstring_parsing.number_of_spaces(x)[source]
contracts.docstring_parsing.parse_annotations(docstring, keys, empty=False, inline_type=False)[source]

Parses “:key name: description” lines into a dictionary mapping name to a description.

If empty is specified, look statements without a name such as “:key: description”.

If inline_type is specified, allow an optional type to be specified parsing “:key type name: description” or “:key type: description”.

enabling Module

class contracts.enabling.Switches[source]
disable_all = False
contracts.enabling.all_disabled()[source]

Returns true if all contracts checks are disabled.

contracts.enabling.disable_all()[source]

Disables all contracts checks.

contracts.enabling.enable_all()[source]

Enables all contracts checks. Can be overridden by an environment variable.

interface Module

exception contracts.interface.CannotDecorateClassmethods[source]

Bases: contracts.interface.ContractDefinitionError

class contracts.interface.Contract(where)[source]

Bases: object

check(value)[source]

Checks that the value satisfies this contract.

Raise:ContractNotRespected
check_contract(context, value, silent)[source]

Checks that value is ok with this contract in the specific context. This is the function that subclasses must implement.

If silent = False, do not bother with creating detailed error messages yet. This is for performance optimization.

Parameters:context – The context in which expressions are evaluated.
disable()[source]
enable()[source]
enabled()[source]
fail(value)[source]

Checks that the value does not respect this contract. Raises an exception if it does.

Raise:ValueError
exception contracts.interface.ContractDefinitionError[source]

Bases: contracts.interface.ContractException

Thrown when defining the contracts

copy()[source]

Returns a copy of the exception so we can re-raise it by erasing the stack.

exception contracts.interface.ContractException[source]

Bases: exceptions.Exception

The base class for the exceptions thrown by this module.

exception contracts.interface.ContractNotRespected(contract, error, value, context)[source]

Bases: contracts.interface.ContractException

Exception thrown when a value does not respect a contract.

exception contracts.interface.ContractSyntaxError(error, where=None)[source]

Bases: contracts.interface.ContractDefinitionError

Exception thrown when there is a syntax error in the contracts.

exception contracts.interface.ExternalScopedVariableNotFound(token)[source]

Bases: contracts.interface.ContractDefinitionError

get_token()[source]
exception contracts.interface.MissingContract[source]

Bases: contracts.interface.ContractException

class contracts.interface.RValue[source]

Bases: object

eval(context)[source]

Can raise ValueError; will be wrapped in ContractNotRespected.

class contracts.interface.Where(string, character, character_end=None)[source]

Bases: object

An object of this class represents a place in a file, or an interval.

All parsed elements contain a reference to a Where object so that we can output pretty error messages.

Character should be >= len(string) (possibly outside the string). Character_end should be >= character (so that you can splice with string[character:character_end])

get_substring()[source]

Returns the substring to which we refer. Raises error if character_end is None

with_filename(filename)[source]
contracts.interface.add_prefix(s, prefix)[source]
contracts.interface.clipped_repr(x, clip)[source]
contracts.interface.describe_type(x)[source]

Returns a friendly description of the type of x.

contracts.interface.describe_value(x, clip=80)[source]

Describes an object, for use in the error messages. Short description, no multiline.

contracts.interface.describe_value_multiline(x)[source]

Describes an object, for use in the error messages.

contracts.interface.eval_in_context(context, value, contract)[source]
contracts.interface.format_table(rows, colspacing=1)[source]
contracts.interface.format_where(w, context_before=3, mark=None, arrow=True, use_unicode=True, no_mark_arrow_if_longer_than=3)[source]
contracts.interface.line_and_col(loc, strg)[source]

Returns (line, col), both 0 based.

contracts.interface.location(line, col, s)[source]
contracts.interface.printable_length_where(w)[source]

Returns the printable length of the substring

contracts.interface.remove_newlines(s)[source]

main Module

class contracts.main.Storage[source]
string2contract = {'np_float32|np_float64': OR([CheckType(float32,'np_float32'), CheckType(float64,'np_float64')]), 'Int|np_scalar_int|(np_scalar,array(int))': OR([CheckType(int,'Int'), Extension('np_scalar_int'), And([Extension('np_scalar'), Array(None,ArrayOR([DType(dtype('int8'),'i1'), DType(dtype('int8')), DType(dtype('int16')), DType(dtype('int32')), DType(dtype('int64'))]))])]), 'np_uint8|np_uint16|np_uint32|np_uint64': OR([CheckType(uint8,'np_uint8'), CheckType(uint16,'np_uint16'), CheckType(uint32,'np_uint32'), CheckType(uint64,'np_uint64')]), 'np_scalar_uint|(np_scalar, array(uint))': OR([Extension('np_scalar_uint'), And([Extension('np_scalar'), Array(None,ArrayOR([DType(dtype('uint8'),'u1'), DType(dtype('uint8')), DType(dtype('uint16')), DType(dtype('uint32')), DType(dtype('uint64'))]))])]), 'np_zeroshape_array|np_scalar_type': OR([Extension('np_zeroshape_array'), Extension('np_scalar_type')]), 'np_scalar_int|np_scalar_uint|np_scalar_float': OR([Extension('np_scalar_int'), Extension('np_scalar_uint'), Extension('np_scalar_float')]), 'np_int8|np_int16|np_int32|np_int64': OR([CheckType(int8,'np_int8'), CheckType(int16,'np_int16'), CheckType(int32,'np_int32'), CheckType(int64,'np_int64')]), 'Float|np_scalar_float|(np_scalar, array(float))': OR([CheckType(float,'Float'), Extension('np_scalar_float'), And([Extension('np_scalar'), Array(None,ArrayOR([DType(dtype('float32')), DType(dtype('float64'))]))])]), 'float|int|uint': OR([Extension('float'), Extension('int'), Extension('uint')])}
contracts.main.check(contract, object, desc=None, **context)[source]

Checks that object satisfies the contract described by contract.

Parameters:
  • contract (str) – The contract string.
  • object (*) – Any object.
  • desc (None|str) – An optional description of the error. If given, it is included in the error message.
contracts.main.check_contracts(contracts, values, context_variables=None)[source]

Checks that the values respect the contract. Not a public function – no friendly messages.

Parameters:
  • contracts (list[N](str),N>0) – List of contracts.
  • values (list[N]) – Values that should match the contracts.
  • context_variables (dict(str[1]: *)) – Initial context
Returns:

a Context variable

Return type:

type(Context)

Raise:

ContractSyntaxError

Raise:

ContractNotRespected

Raise:

ValueError

contracts.main.check_multiple(couples, desc=None)[source]

Checks multiple couples of (contract, value) in the same context.

This means that the variables in each contract are shared with the others.

Parameters:
  • couples (list[>0](tuple(str, *))) – A list of tuple (contract, value) to check.
  • desc (None|str) – An optional description of the error. If given, it is included in the error message.
contracts.main.check_param_is_string(x)[source]
contracts.main.contract_decorator(*arg, **kwargs)[source]

Decorator for adding contracts to functions.

It is smart enough to support functions with variable number of arguments and keyword arguments.

There are three ways to specify the contracts. In order of precedence:

  • As arguments to this decorator. For example:

    @contract(a='int,>0',b='list[N],N>0',returns='list[N]')
    def my_function(a, b):
        # ...
        pass
    
  • As annotations (supported only in Python 3):

    @contract
    def my_function(a:'int,>0', b:'list[N],N>0') -> 'list[N]':
        # ...
        pass
    
  • Using :type: and :rtype: tags in the function’s docstring:

    @contract
    def my_function(a, b):
    
contracts.main.contracts_decorate(function_, modify_docstring=True, **kwargs)[source]

An explicit way to decorate a given function. The decorator decorate() calls this function internally.

contracts.main.fail(contract, value, **initial_context)[source]
Checks that the value does not respect this contract.
Raises an exception if it does.
Raise:ValueError
contracts.main.get_all_arg_names(function)[source]
contracts.main.get_annotations(function)[source]
contracts.main.is_param_string(x)[source]
contracts.main.new_contract(*args)[source]

Defines a new contract type. Used both as a decorator and as a function.

1) Use as a function. The first parameter must be a string. The second parameter can be either a string or a callable function.

new_contract('new_contract_name', 'list[N]')
new_contract('new_contract_name', lambda x: isinstance(x, list) )
  • If it is a string, it is interpreted as contract expression; the given identifier will become an alias for that expression.

  • If it is a callable, it must accept one parameter, and either:

    • return True or None, to signify it accepts.
    • return False or raise ValueError or AssertionError, to signify it doesn’t.

    If ValueError is raised, its message is used in the error.

2) Use as a decorator.

Or, it can be used as a decorator (without arguments). The function name is used as the identifier.

@new_contract
def new_contract_name(x):
    return isinstance(x, list)

This function returns a Contract object. It might be useful to check right away if the declaration is what you meant, using Contract.check() and Contract.fail().

Parameters:
  • identifier (str) – The identifier must be a string not already in use (you cannot redefine list, tuple, etc.).
  • condition (type|callable|str) – Definition of the new contract.
Returns:

The equivalent contract – might be useful for debugging.

Return type:

Contract

contracts.main.new_contract_impl(identifier, condition)[source]
contracts.main.parse_contract_string(string)[source]
contracts.main.parse_contracts_from_docstring(function)[source]
contracts.main.parse_flexible_spec(spec)[source]

spec can be either a Contract, a type, or a contract string. In the latter case, the usual parsing takes place

pyparsing_utils Module

contracts.pyparsing_utils.myOperatorPrecedence(baseExpr, opList)[source]

Helper method for constructing grammars of expressions made up of operators working in a precedence hierarchy. Operators may be unary or binary, left- or right-associative. Parse actions can also be attached to operator expressions.

Parameters:
  • baseExpr - expression representing the most basic element for the

  • opList - list of tuples, one for each operator precedence level in expression grammar; each tuple is of the form (opExpr, numTerms, rightLeftAssoc, parseAction), where:

    • opExpr is the pyparsing expression for the operator;
      may also be a string, which will be converted to a Literal; if numTerms is 3, opExpr is a tuple of two expressions, for the two operators separating the 3 terms
    • numTerms is the number of terms for this operator (must
      be 1, 2, or 3)
    • rightLeftAssoc is the indicator whether the operator is
      right or left associative, using the pyparsing-defined constants opAssoc.RIGHT and opAssoc.LEFT.
    • parseAction is the parse action to be associated with
      expressions matching this operator expression (the parse action tuple member may be omitted)

syntax Module

class contracts.syntax.ParsingTmp[source]
contract_types = ["*", "#", Context separation construct, "Int", "Float", "Number", "bool", {"type" - Suppress:("(") - Forward: ... - Suppress:(")")}, {"string" [{"[" - Forward: ... - "]"}]}, {"str" [{"[" - Forward: ... - "]"}]}, {"unicode" [{"[" - Forward: ... - "]"}]}, List contract, Seq contract, tuple contract, {"dict" [{Suppress:("[") - Forward: ... - Suppress:("]")}] [{"(" - [Forward: ...] ":" [Forward: ...] - ")"}]}, {"map" [{Suppress:("[") - Forward: ... - Suppress:("]")}] [{"(" - [Forward: ...] ":" [Forward: ...] - ")"}]}, Set contract, {"attr" - "(" - Dict:(Group:({{W:(ABCD...) Suppress:(":")} Forward: ...}) [; Group:({{W:(ABCD...) Suppress:(":")} Forward: ...})]...) - ")"}, "file", {[Forward: ...] ">=" Forward: ...}, {[Forward: ...] "==" Forward: ...}, {[Forward: ...] "=" Forward: ...}, {[Forward: ...] "<=" Forward: ...}, {[Forward: ...] != Forward: ...}, {[Forward: ...] "<" Forward: ...}, {[Forward: ...] ">" Forward: ...}, "np_uint16", "np_int64", "np_int8", "np_complex128", "np_uint8", "np_complex64", "np_float16", "np_complex", "np_int", "np_uint32", "np_float32", "np_float", "np_int32", "np_int16", "np_uint64", "np_float64", array() contract, shape() contract, {"isinstance" - Suppress:("(") - W:(ABCD...) - Suppress:(")")}, {a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | w | v | x | y | z FollowedBy:(~{a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | w | v | y | z | * | - | + | / | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | W | V | X | Y | Z | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | _ | x})}, {A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | W | V | X | Y | Z FollowedBy:(~{a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | w | v | y | z | * | - | + | / | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | W | V | X | Y | Z | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | _})}, rvalue]
keywords = ['Int', 'Float', 'Number', 'bool', 'type', 'string', 'str', 'unicode', 'list', 'seq', 'tuple', 'dict', 'map', 'set', 'attr', 'file', 'np_uint16', 'np_int64', 'np_int8', 'np_complex128', 'np_uint8', 'np_complex64', 'np_float16', 'np_complex', 'np_int', 'np_uint32', 'np_float32', 'np_float', 'np_int32', 'np_int16', 'np_uint64', 'np_float64', 'array', 'ndarray', 'shape', 'isinstance']
contracts.syntax.add_contract(x)[source]
contracts.syntax.add_keyword(x)[source]

Declares that x is a keyword — this is useful to have more clear messages. “keywords” are not parsed by Extension. (see extensions.py) and allows to have “deep” error indications. See http://pyparsing.wikispaces.com/message/view/home/620225 and the discussion of the “-” operator in the docs.

contracts.syntax.isnumber(x)[source]

test_registrar Module

contracts.test_registrar.fail(a, b, exact=True)[source]
contracts.test_registrar.good(a, b, exact=True)[source]
contracts.test_registrar.semantic_fail(a, b, exact=True)[source]
contracts.test_registrar.syntax_fail(s)[source]