• Stars
    star
    397
  • Rank 108,561 (Top 3 %)
  • Language
    Python
  • License
    Other
  • Created almost 14 years ago
  • Updated 23 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PyContracts is a Python package that allows to declare constraints on function parameters and return values. Contracts can be specified using Python3 annotations, or inside a docstring. PyContracts supports a basic type system, variables binding, arithmetic constraints, and has several specialized contracts and an extension API.
https://circleci.com/gh/AndreaCensi/contracts.svg?style=svg

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

As a quick intro, please see this presentation about PyContracts.

A presentation about PyContracts
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, which propagates contracts to the subclasses:

from contracts import contract, ContractsMeta, with_metaclass

class Base(with_metaclass(ContractsMeta, object)):

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

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

Numpy: There is special support for Numpy:

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

Status: The syntax is stable and it won't be changed. PyContracts is very well tested on Python 2.x.

Status on Python 3.x: We reached feature parity! Everything works on Python 3 now.

Contributors:

  • Chris Beaumont (Harvard-Smithsonian Center for Astrophysics): $var syntax; kwargs/args for extensions.
  • Brett Graham (Rowland Institute at Harvard University): attr(name:type) syntax for checking types of attributes.
  • William Furr: bug reports and performance improvements
  • Karol Kuczmarski (Google Zurich): implementation of "string" and "unicode" contracts
  • Maarten Derickx (Leiden U.): documentation fixes
  • Calen Pennington (EdX): disabling checks inside check() function.
  • Adam Palay (EdX): implementation of environment variable enabling/disabling override.
  • Ryan Heimbuch: bug reports
  • Bernhard Biskup: bug reports
  • asharp: bug fixes
  • Dennis Kempin (Google mothership): Sphinx-style constraints specs
  • Andy Hayden: Python 3 support, more efficient Numpy checks
  • Jonathan Sharpe: contracts for file-like objects, not operator

(Please let me know if I forgot anybody.)

More Repositories

1

csm

The C(canonical) Scan Matcher
C
235
star
2

calibration

Supplemental material for "Simultaneous calibration of odometry and sensor parameters for mobile robots"
C++
79
star
3

geometry

Library for handling various differentiable manifolds.
Python
49
star
4

compmake

Compmake is a non-obtrusive module that provides Makefile-like facilities (including parallel processing) for batch Python applications.
Python
18
star
5

gpc

Solution for the generalized point correspondence problem in C,Matlab,Ruby
C
16
star
6

2x2_matrix_eigenvalues

C
15
star
7

busymail

Scripts for extracting and plotting statistics from an IMAP account
Python
11
star
8

dvs_tracking

copy over of old dvs_tracking repo
C++
7
star
9

CDE

CDE: automatic packaging of Code, Data, and Environment
C
7
star
10

env_dvs

Environment for the Python code for IROS'13 DVS paper
Shell
6
star
11

flydra_render

Python
4
star
12

writingtools

Tools for writing papers: my .bib files, my Makefiles, my tex macros.
TeX
4
star
13

geometric_saccade_detector

Geometric Fly Saccade Detector
Python
4
star
14

robot-design-game-extra

Extra information for the cards of the Robot Design Game.
4
star
15

saccade_analysis

Extraction and analysis tools for fly saccades
Python
3
star
16

ros_node_utils

Python
3
star
17

efpno

A Python library for the solution of pose network optimization problems
Python
3
star
18

pysnip

Executing Python snippets from LaTeX
Python
3
star
19

patience

a simple script I use privately to manage multiple git repositories
Python
3
star
20

dynamics

A few simple robot dynamics integrators
Python
2
star
21

tmp4-renamed1-feb14-d

This is the description edited
2
star
22

raytracer

simple C++ raytracer with JSON input/output
C
2
star
23

rcl

Retinal Camera Localization
Python
2
star
24

surf12adam

Repository for SURF 2012
Python
2
star
25

me132_students

Code and data for the ME132 (advanced robotics) class at Caltech, winter 2011
C++
2
star
26

boot_agents

Python
1
star
27

tmdp

Reimplementing Tishby's work
Python
1
star
28

json-c

my modifications to json-c
C
1
star
29

stochastic_testing

Some experiments in writing "stochastic" unit tests
Python
1
star
30

boot12env

Shell
1
star
31

task-driven-representations.mit.edu

HTML
1
star
32

snp_env

Shell
1
star
33

vehicles

Python
1
star
34

conf_tools

Tools for managing YAML configuration of projects
Python
1
star
35

cbc

Correlation-based calibration
Python
1
star
36

fancymath

Simple text to unicode translation of math symbols
Python
1
star
37

boot_olympics

Python
1
star
38

bvexp201007

Bootstrapping experiments for summer 2010
Python
1
star
39

be1008

Python
1
star
40

PyQuadStick

An cross-platform Python package for quadrotor flight-simulator control (R/C; joystick; PS3 etc.)
Python
1
star
41

bvenv

Environment for bootstrapping simulations (master git project)
Python
1
star
42

bvapps

Python
1
star
43

utils

Python
1
star
44

behaviors_env

1
star
45

latex_symbol_list

Simple script to create a reference symbols table from a .tex definitions file.
Python
1
star
46

fly_behaviors

Python
1
star
47

reprep

Reproducible Reports
HTML
1
star
48

procgraph_rawseeds

Rawseeds models for procgraph.
Python
1
star
49

latex_gen

Some routines for generating LaTeX documents from Python.
Python
1
star
50

pybv

Python/C++ simulator and related utils for bootstrapping simulations
Python
1
star
51

jsonstream

simple util for reading JSON objects incrementally from a stream
Python
1
star
52

env_calib

Shell
1
star