icontract


Nameicontract JSON
Version 2.7.1 PyPI version JSON
download
home_pagehttps://github.com/Parquery/icontract
SummaryProvide design-by-contract with informative violation messages.
upload_time2024-09-21 05:49:46
maintainerNone
docs_urlNone
authorMarko Ristin
requires_pythonNone
licenseLicense :: OSI Approved :: MIT License
keywords design-by-contract precondition postcondition validation
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            icontract
=========
.. image:: https://github.com/Parquery/icontract/workflows/CI/badge.svg
    :target: https://github.com/Parquery/icontract/actions?query=workflow%3ACI
    :alt: Continuous integration

.. image:: https://coveralls.io/repos/github/Parquery/icontract/badge.svg?branch=master
    :target: https://coveralls.io/github/Parquery/icontract

.. image:: https://badge.fury.io/py/icontract.svg
    :target: https://badge.fury.io/py/icontract
    :alt: PyPI - version

.. image:: https://img.shields.io/pypi/pyversions/icontract.svg
    :alt: PyPI - Python Version

.. image:: https://readthedocs.org/projects/icontract/badge/?version=latest
    :target: https://icontract.readthedocs.io/en/latest/
    :alt: Documentation

.. image:: https://badges.gitter.im/gitterHQ/gitter.svg
    :target: https://gitter.im/Parquery-icontract/community
    :alt: Gitter chat

icontract provides `design-by-contract <https://en.wikipedia.org/wiki/Design_by_contract>`_ to Python3 with informative
violation messages and inheritance.

It also gives a base for a flourishing of a wider ecosystem:

* A linter `pyicontract-lint`_,
* A sphinx plug-in `sphinx-icontract`_,
* A tool `icontract-hypothesis`_ for automated testing and ghostwriting test files which infers
  `Hypothesis`_ strategies based on the contracts,

  * together with IDE integrations such as
    `icontract-hypothesis-vim`_,
    `icontract-hypothesis-pycharm`_, and
    `icontract-hypothesis-vscode`_,
* Directly integrated into `CrossHair`_, a tool for automatic verification of Python programs,

  * together with IDE integrations such as
    `crosshair-pycharm`_ and `crosshair-vscode`_, and
* An integration with `FastAPI`_ through `fastapi-icontract`_ to enforce contracts on your HTTP API and display them
  in OpenAPI 3 schema and Swagger UI, and
* An extensive corpus, `Python-by-contract corpus`_, of Python programs annotated with contracts for educational, testing and research purposes.

.. _pyicontract-lint: https://pypi.org/project/pyicontract-lint
.. _sphinx-icontract: https://pypi.org/project/sphinx-icontract
.. _icontract-hypothesis: https://github.com/mristin/icontract-hypothesis
.. _Hypothesis: https://hypothesis.readthedocs.io/en/latest/
.. _icontract-hypothesis-vim: https://github.com/mristin/icontract-hypothesis-vim
.. _icontract-hypothesis-pycharm: https://github.com/mristin/icontract-hypothesis-pycharm
.. _icontract-hypothesis-vscode: https://github.com/mristin/icontract-hypothesis-vscode
.. _CrossHair: https://github.com/pschanely/CrossHair
.. _crosshair-pycharm: https://github.com/mristin/crosshair-pycharm/
.. _crosshair-vscode: https://github.com/mristin/crosshair-vscode/
.. _FastAPI: https://github.com/tiangolo/fastapi/issues/1996
.. _fastapi-icontract: https://pypi.org/project/fastapi-icontract/
.. _Python-by-contract corpus: https://github.com/mristin/python-by-contract-corpus

Related Projects
----------------
There exist a couple of contract libraries. However, at the time of this writing (September 2018), they all required the
programmer either to learn a new syntax (`PyContracts <https://pypi.org/project/PyContracts/>`_) or to write
redundant condition descriptions (
*e.g.*,
`contracts <https://pypi.org/project/contracts/>`_,
`covenant <https://github.com/kisielk/covenant>`_,
`deal <https://github.com/life4/deal>`_,
`dpcontracts <https://pypi.org/project/dpcontracts/>`_,
`pyadbc <https://pypi.org/project/pyadbc/>`_ and
`pcd <https://pypi.org/project/pcd>`_).

This library was strongly inspired by them, but we go two steps further.

First, our violation message on contract breach are much more informative. The message includes the source code of the
contract condition as well as variable values at the time of the breach. This promotes don't-repeat-yourself principle
(`DRY <https://en.wikipedia.org/wiki/Don%27t_repeat_yourself>`_) and spare the programmer the tedious task of repeating
the message that was already written in code.

Second, icontract allows inheritance of the contracts and supports weakining of the preconditions
as well as strengthening of the postconditions and invariants. Notably, weakining and strengthening of the contracts
is a feature indispensable for modeling many non-trivial class hierarchies. Please see Section
`Inheritance <https://icontract.readthedocs.io/en/latest/usage.html#inheritance>`_.
To the best of our knowledge, there is currently no other Python library that supports inheritance of the contracts in a
correct way.

In the long run, we hope that design-by-contract will be adopted and integrated in the language. Consider this library
a work-around till that happens. You might be also interested in the archived discussion on how to bring
design-by-contract into Python language on
`python-ideas mailing list <https://groups.google.com/forum/#!topic/python-ideas/JtMgpSyODTU>`_.

Teasers
=======
We give a couple of teasers here to motivate the library.
Please see the documentation available on `icontract.readthedocs.io
<https://icontract.readthedocs.io/en/latest/>`_ for a full scope of its
capabilities.

The script is also available as a `repl.it post`_.

.. _repl.it post: https://repl.it/talk/share/icontract-example-script/121190

.. code-block:: python

    >>> import icontract

    >>> @icontract.require(lambda x: x > 3)
    ... def some_func(x: int, y: int = 5) -> None:
    ...     pass
    ...

    >>> some_func(x=5)

    # Pre-condition violation
    >>> some_func(x=1)
    Traceback (most recent call last):
      ...
    icontract.errors.ViolationError: File <doctest README.rst[1]>, line 1 in <module>:
    x > 3:
    x was 1
    y was 5

    # Pre-condition violation with a description
    >>> @icontract.require(lambda x: x > 3, "x must not be small")
    ... def some_func(x: int, y: int = 5) -> None:
    ...     pass
    ...
    >>> some_func(x=1)
    Traceback (most recent call last):
      ...
    icontract.errors.ViolationError: File <doctest README.rst[4]>, line 1 in <module>:
    x must not be small: x > 3:
    x was 1
    y was 5

    # Pre-condition violation with more complex values
    >>> class B:
    ...     def __init__(self) -> None:
    ...         self.x = 7
    ...
    ...     def y(self) -> int:
    ...         return 2
    ...
    ...     def __repr__(self) -> str:
    ...         return "instance of B"
    ...
    >>> class A:
    ...     def __init__(self) -> None:
    ...         self.b = B()
    ...
    ...     def __repr__(self) -> str:
    ...         return "instance of A"
    ...
    >>> SOME_GLOBAL_VAR = 13
    >>> @icontract.require(lambda a: a.b.x + a.b.y() > SOME_GLOBAL_VAR)
    ... def some_func(a: A) -> None:
    ...     pass
    ...
    >>> an_a = A()
    >>> some_func(an_a)
    Traceback (most recent call last):
      ...
    icontract.errors.ViolationError: File <doctest README.rst[9]>, line 1 in <module>:
    a.b.x + a.b.y() > SOME_GLOBAL_VAR:
    SOME_GLOBAL_VAR was 13
    a was instance of A
    a.b was instance of B
    a.b.x was 7
    a.b.y() was 2

    # Post-condition
    >>> @icontract.ensure(lambda result, x: result > x)
    ... def some_func(x: int, y: int = 5) -> int:
    ...     return x - y
    ...
    >>> some_func(x=10)
    Traceback (most recent call last):
      ...
    icontract.errors.ViolationError: File <doctest README.rst[12]>, line 1 in <module>:
    result > x:
    result was 5
    x was 10
    y was 5


    # Pre-conditions fail before post-conditions.
    >>> @icontract.ensure(lambda result, x: result > x)
    ... @icontract.require(lambda x: x > 3, "x must not be small")
    ... def some_func(x: int, y: int = 5) -> int:
    ...    return x - y
    ...
    >>> some_func(x=3)
    Traceback (most recent call last):
      ...
    icontract.errors.ViolationError: File <doctest README.rst[14]>, line 2 in <module>:
    x must not be small: x > 3:
    x was 3
    y was 5

    # Invariant
    >>> @icontract.invariant(lambda self: self.x > 0)
    ... class SomeClass:
    ...     def __init__(self) -> None:
    ...         self.x = -1
    ...
    ...     def __repr__(self) -> str:
    ...         return "an instance of SomeClass"
    ...
    >>> some_instance = SomeClass()
    Traceback (most recent call last):
     ...
    icontract.errors.ViolationError: File <doctest README.rst[16]>, line 1 in <module>:
    self.x > 0:
    self was an instance of SomeClass
    self.x was -1


Installation
============

* Install icontract with pip:

.. code-block:: bash

    pip3 install icontract

Versioning
==========
We follow `Semantic Versioning <http://semver.org/spec/v1.0.0.html>`_. The version X.Y.Z indicates:

* X is the major version (backward-incompatible),
* Y is the minor version (backward-compatible), and
* Z is the patch version (backward-compatible bug fix).

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/Parquery/icontract",
    "name": "icontract",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "design-by-contract precondition postcondition validation",
    "author": "Marko Ristin",
    "author_email": "marko@ristin.ch",
    "download_url": "https://files.pythonhosted.org/packages/3d/d9/3c2a6656faf40ce30ead1bffbcf413db6aa5695dcd9a187eca291cc027d9/icontract-2.7.1.tar.gz",
    "platform": null,
    "description": "icontract\n=========\n.. image:: https://github.com/Parquery/icontract/workflows/CI/badge.svg\n    :target: https://github.com/Parquery/icontract/actions?query=workflow%3ACI\n    :alt: Continuous integration\n\n.. image:: https://coveralls.io/repos/github/Parquery/icontract/badge.svg?branch=master\n    :target: https://coveralls.io/github/Parquery/icontract\n\n.. image:: https://badge.fury.io/py/icontract.svg\n    :target: https://badge.fury.io/py/icontract\n    :alt: PyPI - version\n\n.. image:: https://img.shields.io/pypi/pyversions/icontract.svg\n    :alt: PyPI - Python Version\n\n.. image:: https://readthedocs.org/projects/icontract/badge/?version=latest\n    :target: https://icontract.readthedocs.io/en/latest/\n    :alt: Documentation\n\n.. image:: https://badges.gitter.im/gitterHQ/gitter.svg\n    :target: https://gitter.im/Parquery-icontract/community\n    :alt: Gitter chat\n\nicontract provides `design-by-contract <https://en.wikipedia.org/wiki/Design_by_contract>`_ to Python3 with informative\nviolation messages and inheritance.\n\nIt also gives a base for a flourishing of a wider ecosystem:\n\n* A linter `pyicontract-lint`_,\n* A sphinx plug-in `sphinx-icontract`_,\n* A tool `icontract-hypothesis`_ for automated testing and ghostwriting test files which infers\n  `Hypothesis`_ strategies based on the contracts,\n\n  * together with IDE integrations such as\n    `icontract-hypothesis-vim`_,\n    `icontract-hypothesis-pycharm`_, and\n    `icontract-hypothesis-vscode`_,\n* Directly integrated into `CrossHair`_, a tool for automatic verification of Python programs,\n\n  * together with IDE integrations such as\n    `crosshair-pycharm`_ and `crosshair-vscode`_, and\n* An integration with `FastAPI`_ through `fastapi-icontract`_ to enforce contracts on your HTTP API and display them\n  in OpenAPI 3 schema and Swagger UI, and\n* An extensive corpus, `Python-by-contract corpus`_, of Python programs annotated with contracts for educational, testing and research purposes.\n\n.. _pyicontract-lint: https://pypi.org/project/pyicontract-lint\n.. _sphinx-icontract: https://pypi.org/project/sphinx-icontract\n.. _icontract-hypothesis: https://github.com/mristin/icontract-hypothesis\n.. _Hypothesis: https://hypothesis.readthedocs.io/en/latest/\n.. _icontract-hypothesis-vim: https://github.com/mristin/icontract-hypothesis-vim\n.. _icontract-hypothesis-pycharm: https://github.com/mristin/icontract-hypothesis-pycharm\n.. _icontract-hypothesis-vscode: https://github.com/mristin/icontract-hypothesis-vscode\n.. _CrossHair: https://github.com/pschanely/CrossHair\n.. _crosshair-pycharm: https://github.com/mristin/crosshair-pycharm/\n.. _crosshair-vscode: https://github.com/mristin/crosshair-vscode/\n.. _FastAPI: https://github.com/tiangolo/fastapi/issues/1996\n.. _fastapi-icontract: https://pypi.org/project/fastapi-icontract/\n.. _Python-by-contract corpus: https://github.com/mristin/python-by-contract-corpus\n\nRelated Projects\n----------------\nThere exist a couple of contract libraries. However, at the time of this writing (September 2018), they all required the\nprogrammer either to learn a new syntax (`PyContracts <https://pypi.org/project/PyContracts/>`_) or to write\nredundant condition descriptions (\n*e.g.*,\n`contracts <https://pypi.org/project/contracts/>`_,\n`covenant <https://github.com/kisielk/covenant>`_,\n`deal <https://github.com/life4/deal>`_,\n`dpcontracts <https://pypi.org/project/dpcontracts/>`_,\n`pyadbc <https://pypi.org/project/pyadbc/>`_ and\n`pcd <https://pypi.org/project/pcd>`_).\n\nThis library was strongly inspired by them, but we go two steps further.\n\nFirst, our violation message on contract breach are much more informative. The message includes the source code of the\ncontract condition as well as variable values at the time of the breach. This promotes don't-repeat-yourself principle\n(`DRY <https://en.wikipedia.org/wiki/Don%27t_repeat_yourself>`_) and spare the programmer the tedious task of repeating\nthe message that was already written in code.\n\nSecond, icontract allows inheritance of the contracts and supports weakining of the preconditions\nas well as strengthening of the postconditions and invariants. Notably, weakining and strengthening of the contracts\nis a feature indispensable for modeling many non-trivial class hierarchies. Please see Section\n`Inheritance <https://icontract.readthedocs.io/en/latest/usage.html#inheritance>`_.\nTo the best of our knowledge, there is currently no other Python library that supports inheritance of the contracts in a\ncorrect way.\n\nIn the long run, we hope that design-by-contract will be adopted and integrated in the language. Consider this library\na work-around till that happens. You might be also interested in the archived discussion on how to bring\ndesign-by-contract into Python language on\n`python-ideas mailing list <https://groups.google.com/forum/#!topic/python-ideas/JtMgpSyODTU>`_.\n\nTeasers\n=======\nWe give a couple of teasers here to motivate the library.\nPlease see the documentation available on `icontract.readthedocs.io\n<https://icontract.readthedocs.io/en/latest/>`_ for a full scope of its\ncapabilities.\n\nThe script is also available as a `repl.it post`_.\n\n.. _repl.it post: https://repl.it/talk/share/icontract-example-script/121190\n\n.. code-block:: python\n\n    >>> import icontract\n\n    >>> @icontract.require(lambda x: x > 3)\n    ... def some_func(x: int, y: int = 5) -> None:\n    ...     pass\n    ...\n\n    >>> some_func(x=5)\n\n    # Pre-condition violation\n    >>> some_func(x=1)\n    Traceback (most recent call last):\n      ...\n    icontract.errors.ViolationError: File <doctest README.rst[1]>, line 1 in <module>:\n    x > 3:\n    x was 1\n    y was 5\n\n    # Pre-condition violation with a description\n    >>> @icontract.require(lambda x: x > 3, \"x must not be small\")\n    ... def some_func(x: int, y: int = 5) -> None:\n    ...     pass\n    ...\n    >>> some_func(x=1)\n    Traceback (most recent call last):\n      ...\n    icontract.errors.ViolationError: File <doctest README.rst[4]>, line 1 in <module>:\n    x must not be small: x > 3:\n    x was 1\n    y was 5\n\n    # Pre-condition violation with more complex values\n    >>> class B:\n    ...     def __init__(self) -> None:\n    ...         self.x = 7\n    ...\n    ...     def y(self) -> int:\n    ...         return 2\n    ...\n    ...     def __repr__(self) -> str:\n    ...         return \"instance of B\"\n    ...\n    >>> class A:\n    ...     def __init__(self) -> None:\n    ...         self.b = B()\n    ...\n    ...     def __repr__(self) -> str:\n    ...         return \"instance of A\"\n    ...\n    >>> SOME_GLOBAL_VAR = 13\n    >>> @icontract.require(lambda a: a.b.x + a.b.y() > SOME_GLOBAL_VAR)\n    ... def some_func(a: A) -> None:\n    ...     pass\n    ...\n    >>> an_a = A()\n    >>> some_func(an_a)\n    Traceback (most recent call last):\n      ...\n    icontract.errors.ViolationError: File <doctest README.rst[9]>, line 1 in <module>:\n    a.b.x + a.b.y() > SOME_GLOBAL_VAR:\n    SOME_GLOBAL_VAR was 13\n    a was instance of A\n    a.b was instance of B\n    a.b.x was 7\n    a.b.y() was 2\n\n    # Post-condition\n    >>> @icontract.ensure(lambda result, x: result > x)\n    ... def some_func(x: int, y: int = 5) -> int:\n    ...     return x - y\n    ...\n    >>> some_func(x=10)\n    Traceback (most recent call last):\n      ...\n    icontract.errors.ViolationError: File <doctest README.rst[12]>, line 1 in <module>:\n    result > x:\n    result was 5\n    x was 10\n    y was 5\n\n\n    # Pre-conditions fail before post-conditions.\n    >>> @icontract.ensure(lambda result, x: result > x)\n    ... @icontract.require(lambda x: x > 3, \"x must not be small\")\n    ... def some_func(x: int, y: int = 5) -> int:\n    ...    return x - y\n    ...\n    >>> some_func(x=3)\n    Traceback (most recent call last):\n      ...\n    icontract.errors.ViolationError: File <doctest README.rst[14]>, line 2 in <module>:\n    x must not be small: x > 3:\n    x was 3\n    y was 5\n\n    # Invariant\n    >>> @icontract.invariant(lambda self: self.x > 0)\n    ... class SomeClass:\n    ...     def __init__(self) -> None:\n    ...         self.x = -1\n    ...\n    ...     def __repr__(self) -> str:\n    ...         return \"an instance of SomeClass\"\n    ...\n    >>> some_instance = SomeClass()\n    Traceback (most recent call last):\n     ...\n    icontract.errors.ViolationError: File <doctest README.rst[16]>, line 1 in <module>:\n    self.x > 0:\n    self was an instance of SomeClass\n    self.x was -1\n\n\nInstallation\n============\n\n* Install icontract with pip:\n\n.. code-block:: bash\n\n    pip3 install icontract\n\nVersioning\n==========\nWe follow `Semantic Versioning <http://semver.org/spec/v1.0.0.html>`_. The version X.Y.Z indicates:\n\n* X is the major version (backward-incompatible),\n* Y is the minor version (backward-compatible), and\n* Z is the patch version (backward-compatible bug fix).\n",
    "bugtrack_url": null,
    "license": "License :: OSI Approved :: MIT License",
    "summary": "Provide design-by-contract with informative violation messages.",
    "version": "2.7.1",
    "project_urls": {
        "Homepage": "https://github.com/Parquery/icontract"
    },
    "split_keywords": [
        "design-by-contract",
        "precondition",
        "postcondition",
        "validation"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ae1126fcfa5ef974447521194a1298bff77b029f6d0e6e27587faefb5b68c398",
                "md5": "50cafd07b6e88c5cec93cae58cb9b280",
                "sha256": "aac4073aebb117f16dcb73b8496209a247fc6b153f203a0648d1065ff8bb81af"
            },
            "downloads": -1,
            "filename": "icontract-2.7.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "50cafd07b6e88c5cec93cae58cb9b280",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 39531,
            "upload_time": "2024-09-21T05:49:44",
            "upload_time_iso_8601": "2024-09-21T05:49:44.313185Z",
            "url": "https://files.pythonhosted.org/packages/ae/11/26fcfa5ef974447521194a1298bff77b029f6d0e6e27587faefb5b68c398/icontract-2.7.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3dd93c2a6656faf40ce30ead1bffbcf413db6aa5695dcd9a187eca291cc027d9",
                "md5": "d2138fbb31806d0870f87080abdbfe7c",
                "sha256": "2e8196754743bd1a3659d66da2ddf1dc0950d01e535c2933bd997b02c6412a03"
            },
            "downloads": -1,
            "filename": "icontract-2.7.1.tar.gz",
            "has_sig": false,
            "md5_digest": "d2138fbb31806d0870f87080abdbfe7c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 64828,
            "upload_time": "2024-09-21T05:49:46",
            "upload_time_iso_8601": "2024-09-21T05:49:46.518224Z",
            "url": "https://files.pythonhosted.org/packages/3d/d9/3c2a6656faf40ce30ead1bffbcf413db6aa5695dcd9a187eca291cc027d9/icontract-2.7.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-09-21 05:49:46",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Parquery",
    "github_project": "icontract",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "icontract"
}
        
Elapsed time: 0.32459s