Skip to main content

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

A brief summary follows. See the full documentation at: <http://andreacensi.github.com/contracts/>

Why: The purpose of PyContracts is not to turn Python into a statically-typed language (albeit you can be as strict as you wish), but, rather, to avoid the time-consuming and obfuscating checking of various preconditions. In fact, more than the type constraints, I found useful the ability to impose value and size constraints. For example, “I need a list of at least 3 positive numbers” can be expressed as list[>=3](number, >0)). If you find that PyContracts is overkill for you, you might want to try a simpler alternative, such as typecheck. If you find that PyContracts is not enough for you, you probably want to be using Haskell instead of Python.

Specifying contracts: Contracts can be specified in three ways:

  1. Using the ``@contract`` decorator:

    @contract(a='int,>0', b='list[N],N>0', returns='list[N]')
    def my_function(a, b):
        ...
  2. Using annotations (for Python 3):

    @contract
    def my_function(a : 'int,>0', b : 'list[N],N>0') -> 'list[N]':
         # Requires b to be a nonempty list, and the return
         # value to have the same length.
         ...
  3. Using docstrings, with the :type: and :rtype: tags:

    @contract
    def my_function(a, b):
        """ Function description.
            :type a: int,>0
            :type b: list[N],N>0
            :rtype: list[N]
        """
        ...

Deployment: In production, all checks can be disabled using the function contracts.disable_all(), so the performance hit is 0.

Extensions: You can extend PyContracts with new contracts types:

new_contract('valid_name', lambda s: isinstance(s, str) and len(s)>0)
@contract(names='dict(int: (valid_name, int))')
def process_accounting(records):
    ...

Any Python type is a contract:

@contract(a=int, # simple contract
          b='int,>0' # more complicated
          )
def f(a, b):
    ...

Enforcing interfaces: ContractsMeta is a metaclass like ABCMeta that propagates contracts to the subclasses:

from contracts import contract, ContractsMeta

class Base(object):
    __metaclass__ = ContractsMeta

    @abstractmethod
    @contract(probability='float,>=0,<=1')
    def sample(probability):
        pass

class Derived(Base):
    # The contract above is automatically enforced,
    # without this class having to know about PyContracts at all!
    def sample(probability):
        ....

Numpy: There is special support for Numpy:

@contract(image='array[HxWx3](uint8),H>10,W>10')
def recolor(image):
    ...

Status: PyContracts is very well tested and documented. The syntax is stable and it won’t be changed.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

PyContracts-1.6.2.tar.gz (50.6 kB view details)

Uploaded Source

File details

Details for the file PyContracts-1.6.2.tar.gz.

File metadata

  • Download URL: PyContracts-1.6.2.tar.gz
  • Upload date:
  • Size: 50.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for PyContracts-1.6.2.tar.gz
Algorithm Hash digest
SHA256 883ce5c1b4faf4debd0dab45b4a5ad90febc40c955af2138ef85b246d69e1103
MD5 7e633c047aa4ae324e5331a1cac9a470
BLAKE2b-256 bd54001602086e154e66114138c5682a2c0f2224e56090be822417f7e64b8bb1

See more details on using hashes here.

Release history Release notifications | RSS feed

1.8.12

1 file

1.8.11

1 file

1.8.10

1 file

1.8.9

1 file

1.8.8

1 file

1.8.7

1 file

1.8.6

1 file

1.8.5

1 file

1.8.4

1 file

1.8.3

1 file

1.8.2

1 file

1.8.1

1 file

1.8.0

1 file

1.7.16

1 file

1.7.15

1 file

1.7.14

1 file

1.7.13

1 file

1.7.12

1 file

1.7.11

1 file

1.7.10

1 file

1.7.9

1 file

1.7.8

1 file

1.7.7

1 file

1.7.6

1 file

1.7.4

1 file

1.7.3

1 file

1.7.2

1 file

1.7.1

1 file

1.7.0

1 file

1.6.6

1 file

1.6.5

1 file

1.6.4

1 file

1.6.3

1 file

This release

1.6.2 This release

1 file

1.6.0

1 file

1.5.1

1 file

1.5.0

1 file

1.4.0

1 file

1.2.0

1 file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page