### Installing icontract Library Source: https://github.com/parquery/icontract/blob/master/README.rst Provides a simple command-line instruction for installing the `icontract` library using pip, the Python package installer. ```bash pip3 install icontract ``` -------------------------------- ### Install Documentation Build Requirements Source: https://github.com/parquery/icontract/blob/master/docs/how-to-build-docs.md Installs the necessary dependencies for building the project documentation, typically including Sphinx and related tools, from the requirements-doc.txt file. This step is crucial before attempting to build the documentation. ```bash pip3 install -r requirements-doc.txt ``` -------------------------------- ### Install icontract Project Requirements Source: https://github.com/parquery/icontract/blob/master/docs/how-to-build-docs.md Installs the core dependencies required for the icontract project using pip from the requirements.txt file. This ensures the project's runtime dependencies are met. ```bash pip3 install -r requirements.txt ``` -------------------------------- ### Enforcing Basic Pre-conditions with icontract.require Source: https://github.com/parquery/icontract/blob/master/README.rst Demonstrates how to use the `@icontract.require` decorator to enforce a basic pre-condition on function arguments. The example shows both a successful function call and a `ViolationError` when the condition is not met, including the traceback. ```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 , line 1 in : # x > 3: # x was 1 # y was 5 ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/parquery/icontract/blob/master/docs/source/development.rst Instructions to install all necessary development dependencies for the project from the current directory into the active virtual environment using `pip3 install -e .[dev]`. ```bash pip3 install -e .[dev] ``` -------------------------------- ### Adding Custom Descriptions to icontract Pre-conditions Source: https://github.com/parquery/icontract/blob/master/README.rst Illustrates how to provide a custom error message for a pre-condition violation by passing a string description as the second argument to the `@icontract.require` decorator. This makes error messages more user-friendly. ```python @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 , line 1 in : # x must not be small: x > 3: # x was 1 # y was 5 ``` -------------------------------- ### Enforcing Post-conditions with icontract.ensure Source: https://github.com/parquery/icontract/blob/master/README.rst Demonstrates the use of the `@icontract.ensure` decorator to verify conditions on a function's return value (`result`) and its input parameters after execution. This helps ensure the function's output meets specified criteria. ```python @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 , line 1 in : # result > x: # result was 5 # x was 10 # y was 5 ``` -------------------------------- ### Complex Pre-conditions with Object Attributes and Global Variables Source: https://github.com/parquery/icontract/blob/master/README.rst Shows how `@icontract.require` can evaluate conditions involving complex expressions, including object attributes, method calls, and global variables. The traceback provides detailed context about the values of involved variables during a violation. ```python 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 , line 1 in : # 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 ``` -------------------------------- ### Build Project Documentation with Sphinx Source: https://github.com/parquery/icontract/blob/master/docs/how-to-build-docs.md Navigates into the 'docs' directory and then uses Sphinx to build the project documentation. The 'source' directory contains the reStructuredText or Markdown files, and the output HTML documentation will be generated into the 'build' directory. The final documentation is located in `docs/build`. ```bash cd docs sphinx-build source build ``` -------------------------------- ### Activate Python Virtual Environment Source: https://github.com/parquery/icontract/blob/master/docs/source/development.rst Instructions to activate the previously created Python virtual environment 'venv3' using the `source` command, making its Python interpreter and installed packages available. ```bash source venv3/bin/activate ``` -------------------------------- ### Python Token Class Initialization with Precondition Source: https://github.com/parquery/icontract/blob/master/docs/source/recipes.rst Defines the constructor for a `Token` class, demonstrating the use of an `@require` decorator from `icontract`. This precondition ensures that the `start` parameter is strictly less than the `end` parameter, enforcing valid range definitions for tokens. ```python class Token(DBC): @require(lambda start, end: start < end) def __init__(self, ..., start: int, end: int, ...) -> None: ... ``` -------------------------------- ### Pre-condition Priority Over Post-conditions in icontract Source: https://github.com/parquery/icontract/blob/master/README.rst Illustrates the order of contract checking: pre-conditions are evaluated before post-conditions. If a pre-condition fails, the function body is not executed, and thus the post-condition is not checked, preventing unnecessary computation and ensuring early error detection. ```python @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 , line 2 in : # x must not be small: x > 3: # x was 3 # y was 5 ``` -------------------------------- ### Enforcing Class Invariants with icontract.invariant Source: https://github.com/parquery/icontract/blob/master/README.rst Shows how to use the `@icontract.invariant` decorator to define conditions that must hold true for an instance of a class throughout its lifecycle, typically checked after initialization or method calls. This ensures the internal state of an object remains consistent. ```python @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 , line 1 in : # self.x > 0: # self was an instance of SomeClass # self.x was -1 ``` -------------------------------- ### Encapsulating Immutable Types with Contracts (Lines Example) Source: https://github.com/parquery/icontract/blob/master/docs/source/recipes.rst Illustrates encapsulating common contracts for immutable data types like `Sequence` into a new custom type. Instead of `__init__`, `__new__` is used to construct the object after pre-conditions are checked. The example shows a `Lines` class ensuring that its sequence of strings does not contain newline characters. ```python class Lines(DBC): """Represent a sequence of text lines.""" # fmt: off @require( lambda lines: all('\n' not in line and '\r' not in line for line in lines) ) # fmt: on def __new__(cls, lines: Sequence[str]) -> "Lines": return cast(Lines, lines) ``` -------------------------------- ### Inheriting Snapshots and Postconditions in Icontract Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst Demonstrates how `icontract.snapshot` and `icontract.ensure` decorators are inherited and composed in subclasses. The example shows a `bug` in the subclass's implementation that leads to a `ViolationError` due to the inherited postcondition. ```python >>> class A(icontract.DBC): ... @abc.abstractmethod ... @icontract.snapshot(lambda lst: lst[:]) ... @icontract.ensure(lambda OLD, lst: len(lst) == len(OLD.lst) + 1) ... def func(self, lst: List[int], value: int) -> None: ... pass >>> class B(A): ... # The snapshot of OLD.lst has been defined in class A. ... @icontract.ensure(lambda OLD, lst: lst == OLD.lst + [value]) ... def func(self, lst: List[int], value: int) -> None: ... lst.append(value) ... lst.append(1984) # bug ... ... def __repr__(self) -> str: ... return "an instance of B" >>> b = B() >>> b.func(lst=[1, 2], value=3) Traceback (most recent call last): ... icontract.errors.ViolationError: File , line 4 in A: len(lst) == len(OLD.lst) + 1: OLD was a bunch of OLD values OLD.lst was [1, 2] len(OLD.lst) was 2 len(lst) was 4 lst was [1, 2, 3, 1984] result was None self was an instance of B value was 3 ``` -------------------------------- ### Python Tokenization Function with Postcondition for Consecutive Tokens Source: https://github.com/parquery/icontract/blob/master/docs/source/recipes.rst Illustrates a `tokenize` function with an `@ensure` postcondition. This contract verifies that all generated tokens are consecutive, meaning the `end` of one token matches the `start` of the subsequent token, using a `common.pairwise` helper. ```python @ensure( lambda result: all( token1.end == token2.start for token1, token2 in common.pairwise(result) ), "Tokens consecutive" ) def tokenize(text: str) -> List[Token]: """Tokenize the given ``text``.""" ... ``` -------------------------------- ### Demonstrating Contract Strengthening in Python with icontract Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst This example illustrates how invariants and postconditions are strengthened when inherited by a child class (`B`) from a parent abstract class (`A`) using `icontract.DBC`. It shows how violating either the parent's or the child's contracts leads to a `ViolationError`, demonstrating the cumulative effect of strengthened contracts. ```python >>> import abc >>> import icontract >>> @icontract.invariant(lambda self: self.x > 0) ... class A(icontract.DBC): ... def __init__(self) -> None: ... self.x = 10 ... ... @abc.abstractmethod ... @icontract.ensure(lambda y, result: result < y) ... def func(self, y: int) -> int: ... pass ... ... def __repr__(self) -> str: ... return "an instance of A" >>> @icontract.invariant(lambda self: self.x < 100) ... class B(A): ... def func(self, y: int) -> int: ... # Break intentionally the postcondition ... # for an illustration ... return y + 1 ... ... def break_parent_invariant(self): ... self.x = -1 ... ... def break_my_invariant(self): ... self.x = 101 ... ... def __repr__(self) -> str: ... return "an instance of B" # Break the parent's postcondition >>> some_b = B() >>> some_b.func(y=0) Traceback (most recent call last): ... icontract.errors.ViolationError: File , line 7 in A: result < y: result was 1 self was an instance of B y was 0 # Break the parent's invariant >>> another_b = B() >>> another_b.break_parent_invariant() Traceback (most recent call last): ... icontract.errors.ViolationError: File , line 1 in : self.x > 0: self was an instance of B self.x was -1 # Break the child's invariant >>> yet_another_b = B() >>> yet_another_b.break_my_invariant() Traceback (most recent call last): ... icontract.errors.ViolationError: File , line 1 in : self.x < 100: self was an instance of B self.x was 101 ``` -------------------------------- ### Measure Basic Python Operation Performance with timeit Source: https://github.com/parquery/icontract/blob/master/benchmarks/benchmark_2.0.7.rst This `bash` command uses Python's `timeit` module to measure the execution time of a simple mathematical operation (`math.sqrt`). It serves as a baseline example to put the `icontract` benchmark results into context, showing typical microsecond-level performance for a single loop. ```bash python3 -m timeit -s 'import math' 'math.sqrt(1984.1234)' ``` -------------------------------- ### Combining Multiple Arguments into a Single Snapshot in Python Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst This example shows how `icontract.snapshot` can capture a combined state derived from multiple function arguments (e.g., the union of two lists). This allows postconditions to verify complex interactions and aggregate state changes across several inputs, ensuring comprehensive contract enforcement. ```python import icontract from typing import List @icontract.snapshot( lambda lst_a, lst_b: set(lst_a).union(lst_b), name="union") @icontract.ensure( lambda OLD, lst_a, lst_b: set(lst_a).union(lst_b) == OLD.union) def some_func(lst_a: List[int], lst_b: List[int]) -> None: lst_a.append(1984) # bug some_func(lst_a=[1, 2], lst_b=[3, 4]) ``` -------------------------------- ### Demonstrating Precondition Weakening in Python with icontract Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst This example shows how preconditions are weakened in a child class (`B`) inheriting from a parent class (`A`) using `icontract.DBC`. The child class's method `func` can satisfy either its own precondition or the parent's precondition, illustrating that the caller has more options to satisfy the contract. ```python >>> class A(icontract.DBC): ... @icontract.require(lambda x: x % 2 == 0) ... def func(self, x: int) -> None: ... pass >>> class B(A): ... @icontract.require(lambda x: x % 3 == 0) ... def func(self, x: int) -> None: ... pass ... ... def __repr__(self) -> str: ... return "an instance of B" >>> b = B() # The precondition of the parent is satisfied. >>> b.func(x=2) # The precondition of the child is satisfied, # while the precondition of the parent is not. ``` -------------------------------- ### Using Snapshots to Verify List Appends in Python Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst This example demonstrates how to use `icontract.snapshot` to capture the initial state of a list argument before a function call. The `icontract.ensure` postcondition then uses this 'OLD' state to verify that a specific value was appended to the list, highlighting how `icontract` can detect unintended modifications or bugs. ```python import icontract from typing import List @icontract.snapshot(lambda lst: lst[:]) @icontract.ensure(lambda OLD, lst, value: lst == OLD.lst + [value]) def some_func(lst: List[int], value: int) -> None: lst.append(value) lst.append(1984) # bug some_func(lst=[1, 2], value=3) ``` -------------------------------- ### Complex Async Contract Checks with asyncstdlib Source: https://github.com/parquery/icontract/blob/master/docs/source/async.rst This comprehensive example demonstrates using `asyncstdlib` functions (`a.map`, `a.all`, `a.await_each`) within `icontract` conditions. It shows how to apply asynchronous checks across collections, such as ensuring all categories are valid (`require`) and all authors of returned books exist (`ensure`), by mapping async predicates and awaiting their results. ```Python import asyncstdlib as a async def has_author(identifier: str) -> bool: ... async def has_category(category: str) -> bool: ... @dataclasses.dataclass class Book: identifier: str author: str @icontract.require(lambda categories: a.map(has_category, categories)) @icontract.ensure( lambda result: a.all(a.await_each(has_author(book.author) for book in result))) async def list_books(categories: List[str]) -> List[Book]: ... ``` -------------------------------- ### Correct order for icontract and dataclass decorators Source: https://github.com/parquery/icontract/blob/master/docs/source/known_issues.rst This example demonstrates the correct order for applying `icontract` and `dataclasses` decorators. The `icontract` decorator must be applied *before* the `@dataclass` decorator to ensure proper functionality, as `dataclass` inserts methods that cannot be re-decorated by `icontract` afterwards. ```python >>> import icontract >>> import dataclasses >>> @icontract.invariant(lambda self: self.x > 0) ... @dataclasses.dataclass ... class Foo: ... x: int = dataclasses.field(default=42) ``` -------------------------------- ### Defining and Enforcing Function Preconditions with icontract.require Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst Demonstrates how to use the `@icontract.require` decorator to define preconditions for Python functions. Examples include basic usage, adding a custom description to the violation message, and handling complex object values and global variables in contract checks. Violations raise `icontract.errors.ViolationError` with detailed context. ```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 , line 1 in : # 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 , line 1 in : # 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 "an instance of B" class A: def __init__(self)->None: self.b = B() def __repr__(self) -> str: return "an 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 , line 1 in : # a.b.x + a.b.y() > SOME_GLOBAL_VAR: # SOME_GLOBAL_VAR was 13 # a was an instance of A # a.b was an instance of B # a.b.x was 7 # a.b.y() was 2 ``` -------------------------------- ### Example of Recursive Function Contracts Source: https://github.com/parquery/icontract/blob/master/docs/source/implementation_details.rst This Python snippet presents a scenario where two functions have preconditions that recursively depend on each other. It sets the context for `icontract`'s mechanism to suspend contract checking upon re-entry to prevent infinite loops. ```Python @icontract.require(lambda: another_func()) def some_func() -> bool: ... @icontract.require(lambda: some_func()) def another_func() -> bool: ... some_func() ``` -------------------------------- ### Example of Recursive Invariant Checks Source: https://github.com/parquery/icontract/blob/master/docs/source/implementation_details.rst This Python snippet demonstrates a class with an invariant that calls an instance method, which could lead to endless recursion during invariant checks. It illustrates how `icontract` prevents this by temporarily suspending further invariant checks. ```Python @icontract.invariant(lambda self: self.some_func()) class SomeClass(icontract.DBC): def __init__(self) -> None: ... def some_func(self) -> bool: ... ``` -------------------------------- ### Applying Async Conditions to Async Functions Source: https://github.com/parquery/icontract/blob/master/docs/source/async.rst This example illustrates how to use an asynchronous function (`has_author`) as a condition within an `icontract.ensure` decorator. It highlights that both the condition function and the decorated function must be asynchronous when enforcing async conditions. ```Python import icontract async def has_author(author_id: str) -> bool: ... @icontract.ensure(has_author) async def upsert_author(name: str) -> str: ... ``` -------------------------------- ### Define icontract.require with Custom Error Message Lambda Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst Demonstrates how to use a lambda function assigned to the `error` argument of `icontract.require` to generate a dynamic, custom error message based on the input value when a contract is violated. The example shows a `ValueError` being raised with a specific message. ```Python @icontract.require( lambda x: x > 0, error=lambda x: ValueError('x must be positive, got: {}'.format(x))) def some_func(x: int) -> int: return 123 ``` -------------------------------- ### Redundant `icontract.require` for Already Type-Annotated Arguments Source: https://github.com/parquery/icontract/blob/master/docs/source/checking_types_at_runtime.rst This example illustrates a less ideal use case where `icontract.require` is applied to an argument that already has a type annotation. While functional, this approach violates the DRY principle, making the code harder to maintain and read by duplicating type information that is already provided by the type hint. ```python @icontract.require(lambda x: isinstance(x, int)) def some_func(x: int) -> None ... ``` -------------------------------- ### Example of Invariant Checks During Object Construction Source: https://github.com/parquery/icontract/blob/master/docs/source/implementation_details.rst This Python snippet shows a class where an invariant depends on an attribute initialized within the constructor. It highlights the necessity of disabling invariant checks during object construction to prevent errors related to accessing uninitialized attributes. ```Python @icontract.invariant(lambda self: self.some_attribute > 0) class SomeClass(icontract.DBC): def __init__(self) -> None: self.some_attribute = self.some_func() def some_func(self) -> int: return 1984 ``` -------------------------------- ### Customizing Icontract Violation Errors with Callables Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst Explains how to specify a custom error to be raised by an `icontract` decorator using the `error` argument. This example shows providing a callable that returns an exception, highlighting its benefit of reduced computational overhead compared to default violation messages. ```python >>> @icontract.require( ``` -------------------------------- ### Run Tox for Testing and Packaging Source: https://github.com/parquery/icontract/blob/master/docs/source/development.rst Instructions to run `tox`, a command-line tool for automating testing and packaging of Python projects, ensuring consistent test environments. ```bash tox ``` -------------------------------- ### Create Python Virtual Environment Source: https://github.com/parquery/icontract/blob/master/docs/source/development.rst Instructions to create a new Python virtual environment named 'venv3' in the repository root using the `python3 -m venv` command. ```bash python3 -m venv venv3 ``` -------------------------------- ### Run Local Pre-commit Checks Source: https://github.com/parquery/icontract/blob/master/docs/source/development.rst Instructions to execute the provided pre-commit checks locally from an activated virtual environment with development dependencies. These checks lint and verify code formatting. ```bash ./precommit.py ``` -------------------------------- ### Format Code with Pre-commit Script Source: https://github.com/parquery/icontract/blob/master/docs/source/development.rst Instructions to automatically format the code using the pre-commit script by providing the `--overwrite` flag, which applies formatting changes directly to the files. ```bash ./precommit.py --overwrite ``` -------------------------------- ### Conditionally Enabling Contracts for Testing Environments Source: https://github.com/parquery/icontract/blob/master/docs/source/recipes.rst Illustrates how to toggle contracts on or off at load time using the `enabled` argument of the `@ensure` decorator. This is particularly useful for applying contracts only in specific environments, such as testing, where performance overhead might be acceptable. ```python IN_TESTING_ENVIRONMENT = ... @ensure( lambda result: all( naive_is_prime(number) for number in result ), enabled=IN_TESTING_ENVIRONMENT ) ``` -------------------------------- ### Importing asyncstdlib for Async Sequence Operations Source: https://github.com/parquery/icontract/blob/master/docs/source/async.rst This snippet shows the standard way to import the `asyncstdlib` library, aliasing it as 'a'. `asyncstdlib` provides asynchronous versions of built-in functions and tools, useful for working with sequences of awaitables in contracts. ```Python import asyncstdlib as a ``` -------------------------------- ### Applying `ensure` for Postconditions with Sieve of Eratosthenes Source: https://github.com/parquery/icontract/blob/master/docs/source/recipes.rst Demonstrates the basic usage of the `@ensure` decorator to verify the postcondition of a function, ensuring that all numbers returned by the Sieve of Eratosthenes algorithm are indeed prime. ```python @ensure( lambda result: all( naive_is_prime(number) for number in result ) ) def sieve(limit: int) -> List[int]: """ Apply the Sieve of Eratosthenes on the numbers up to ``limit``. :return: list of prime numbers till ``limit`` """ ... ``` -------------------------------- ### Python Function with Assert Precondition Source: https://github.com/parquery/icontract/blob/master/benchmarks/benchmark_2.0.7.rst Illustrates a `my_sqrt` function where the precondition (`x >= 0`) is checked using a standard Python `assert` statement. ```Python def my_sqrt(x: float) -> float: assert x >= 0 return math.sqrt(x) ``` -------------------------------- ### Demonstrating Icontract Precondition Violations Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst Illustrates how `icontract` enforces preconditions, showing a successful call when a precondition is met or weakened, and a `ViolationError` when preconditions are not satisfied, along with the detailed traceback. ```python # This is OK since the precondition has been # weakened. >>> b.func(x=3) # None of the preconditions have been satisfied. >>> b.func(x=5) Traceback (most recent call last): ... icontract.errors.ViolationError: File , line 2 in B: x % 3 == 0: self was an instance of B x was 5 ``` -------------------------------- ### Executing Python Tests with `ICONTRACT_SLOW` Enabled Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst Provides the bash command to run a Python unit test script, demonstrating how to activate contracts marked with `icontract.SLOW` by setting the `ICONTRACT_SLOW` environment variable before execution. ```bash $ ICONTRACT_SLOW=true python test_some_module.py ``` -------------------------------- ### Python Function with icontract Precondition Source: https://github.com/parquery/icontract/blob/master/benchmarks/benchmark_2.0.7.rst Demonstrates the use of the `icontract` library to define a precondition (`x >= 0`) for the `my_sqrt` function using the `@icontract.require` decorator. ```Python import math import icontract @icontract.require(lambda x: x >= 0) def my_sqrt(x: float) -> float: return math.sqrt(x) ``` -------------------------------- ### Python Bin Index Function with Material Conditional Postcondition Source: https://github.com/parquery/icontract/blob/master/docs/source/recipes.rst Demonstrates how to use a material conditional (`not A or B`) within an `@ensure` contract for the `bin_index` function. This postcondition ensures that if a `value` is not covered by any range (i.e., `value < ranges[0].start`), then the function's `result` must be -1, effectively handling edge cases for bin lookup. ```python class Range: start: Final[float] end: Final[float] ... @ensure( lambda ranges, value, result: not (value < ranges[0].start) or result == -1, "Value not covered in ranges => bin not found" ) def bin_index(ranges: BinRanges, value: float) -> int: """Find the index of the bin range among ``ranges`` corresponding to ``value``.""" ... ``` -------------------------------- ### API Reference: icontract.snapshot Class Source: https://github.com/parquery/icontract/blob/master/docs/source/api.rst Documents the `snapshot` class from the `icontract` library, used for capturing the state of variables before or after a function execution, typically for postcondition checks. It includes its constructor and callable interface. ```APIDOC icontract.snapshot: Type: Class Description: Captures variable states for contract checks. Methods: __init__(): Description: Initializes the snapshot instance. __call__(): Description: Captures the specified variable's value. ``` -------------------------------- ### Validate Table Layout with Multiple icontract Preconditions Source: https://github.com/parquery/icontract/blob/master/docs/source/recipes.rst This snippet demonstrates using multiple `icontract` `@require` decorators to enforce complex preconditions on a 2D list representing a `Layout`. It ensures the table is non-empty, rows have consistent lengths, and all cells match a specific regex pattern. This comprehensive validation guarantees valid input for the `Layout` class initialization. ```python import re class Layout: """Represent a seat layout.""" @require( lambda table: len(table) > 0 and len(table[0]) > 0 and all( len(row) == len(table[0]) for row in table ) ) @require( lambda table: all( re.fullmatch(r"[L#.]", cell) for row in table for cell in row ) ) def __init__(self, table: List[List[str]]) -> None: """Initialize with the given values.""" ... ``` -------------------------------- ### Define icontract.require with Exception Instance Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst Shows how to provide an already instantiated exception object (e.g., `ValueError("x non-positive")`) to the `error` argument of `icontract.require`. This allows for a fixed, predefined error message to be raised upon contract violation. ```Python @icontract.require(lambda x: x > 0, error=ValueError("x non-positive")) def some_func(x: int) -> int: return 123 ``` -------------------------------- ### Contract Inheritance with icontract.DBC and DBCMeta Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst This API documentation explains the mechanisms for ensuring correct contract inheritance in `icontract`. It details how child classes must inherit from `icontract.DBC` or use `icontract.DBCMeta` as a metaclass to properly inherit invariants, preconditions, and postconditions from parent classes, preventing undefined behavior and maintaining the Liskov substitution principle. ```APIDOC DBC Class and icontract.DBCMeta Metaclass for Contract Inheritance: To inherit contracts (invariants, preconditions, postconditions) from a parent class, a child class must: 1. Inherit directly from `icontract.DBC`. Example: `class ChildClass(ParentClass, icontract.DBC):` 2. Or, set its metaclass to `icontract.DBCMeta`. Example: `class ChildClass(ParentClass, metaclass=icontract.DBCMeta):` Purpose: Ensures correct inheritance and prevents contract leakage from child to parent classes. Without this, contract inheritance behavior is undefined and may violate the Liskov substitution principle. ``` -------------------------------- ### API Reference: icontract.require Class Source: https://github.com/parquery/icontract/blob/master/docs/source/api.rst Documents the `require` class from the `icontract` library, which is used to define preconditions for functions or methods in a design-by-contract paradigm. It includes its constructor and callable interface. ```APIDOC icontract.require: Type: Class Description: Represents a precondition in design-by-contract. Methods: __init__(): Description: Initializes the require instance. __call__(): Description: Executes the precondition check. ``` -------------------------------- ### API Reference: icontract.DBCMeta Class Source: https://github.com/parquery/icontract/blob/master/docs/source/api.rst Documents the `DBCMeta` class from the `icontract` library, which likely serves as a metaclass for classes that implement design-by-contract features. ```APIDOC icontract.DBCMeta: Type: Class Description: Metaclass for design-by-contract functionality. ``` -------------------------------- ### API Reference: icontract.ensure Class Source: https://github.com/parquery/icontract/blob/master/docs/source/api.rst Documents the `ensure` class from the `icontract` library, which is used to define postconditions for functions or methods. It includes its constructor and callable interface. ```APIDOC icontract.ensure: Type: Class Description: Represents a postcondition in design-by-contract. Methods: __init__(): Description: Initializes the ensure instance. __call__(): Description: Executes the postcondition check. ``` -------------------------------- ### Naming Snapshots for Specific Argument Properties in Python Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst This snippet illustrates how to explicitly name a snapshot using the `name` argument in `icontract.snapshot`. By capturing `len(lst)` and naming it 'len_lst', the postcondition can precisely verify changes to the list's length, demonstrating fine-grained control over state verification. ```python import icontract from typing import List @icontract.snapshot(lambda lst: len(lst), name="len_lst") @icontract.ensure(lambda OLD, lst, value: len(lst) == OLD.len_lst + 1) def some_func(lst: List[int], value: int) -> None: lst.append(value) lst.append(1984) # bug some_func(lst=[1, 2], value=3) ``` -------------------------------- ### Python Function without Precondition Source: https://github.com/parquery/icontract/blob/master/benchmarks/benchmark_2.0.7.rst Defines a baseline `my_sqrt` function that computes the square root without any precondition checks, serving as a performance reference. ```Python import math def my_sqrt(x: float) -> float: return math.sqrt(x) ``` -------------------------------- ### Python Function with Encapsulated Precondition Source: https://github.com/parquery/icontract/blob/master/benchmarks/benchmark_2.0.7.rst Shows a `my_sqrt` function where a more complex precondition is encapsulated within a separate helper function `check_non_negative`, which uses an `assert`. ```Python import math def check_non_negative(x: float) -> None: assert x >= 0 def my_sqrt(x: float) -> float: check_non_negative(x) return math.sqrt(x) ``` -------------------------------- ### Bash Command for Measuring Function Performance Source: https://github.com/parquery/icontract/blob/master/benchmarks/benchmark_2.0.7.rst A bash command using the `timeit` module to measure the execution time of the `my_sqrt` function, after importing its module. ```Bash $ python3 -m timeit -s 'import my_sqrt' 'my_sqrt.my_sqrt(1984.1234)' ``` -------------------------------- ### Conditional Contract Execution with `icontract.SLOW` Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst Illustrates the use of `icontract.SLOW` for enabling contracts conditionally, typically for development or testing environments. This mechanism allows marking contracts that are too performance-intensive for production, and activating them via the `ICONTRACT_SLOW` environment variable. ```python # some_module.py @icontract.require(lambda x: x > 10, enabled=icontract.SLOW) def some_func(x: int) -> int: return 123 # in test_some_module.py import unittest class TestSomething(unittest.TestCase): def test_some_func(self) -> None: self.assertEqual(123, some_func(15)) if __name__ == '__main__': unittest.main() ``` -------------------------------- ### Limiting Contract Application with Material Conditional Source: https://github.com/parquery/icontract/blob/master/docs/source/recipes.rst Explains how to use a material conditional (logical implication) within an `@ensure` contract to limit its application to specific runtime conditions. This pattern allows the contract to be checked only when a preceding condition is met, such as for small inputs. ```python IN_TESTING_ENVIRONMENT = ... @ensure( lambda result: not (max(result) < 100 and len(result) <= 10) or all( naive_is_prime(number) for number in result ) ) ``` -------------------------------- ### API Reference: icontract.DBC Class Source: https://github.com/parquery/icontract/blob/master/docs/source/api.rst Documents the `DBC` class from the `icontract` library, which is likely a base class for objects that incorporate design-by-contract principles. ```APIDOC icontract.DBC: Type: Class Description: Base class for design-by-contract objects. ``` -------------------------------- ### Demonstrating Precondition Decorator Stacking Behavior Source: https://github.com/parquery/icontract/blob/master/docs/source/implementation_details.rst This Python snippet illustrates how `icontract.require` decorators interact when mixed with other custom decorators. It highlights that preconditions are verified at the innermost decorator, which might lead to unexpected timing if not explicitly grouped. ```Python @some_custom_decorator @icontract.require(lambda x: x > 0) @another_custom_decorator @icontract.require(lambda x, y: y < x) def some_func(x: int, y: int) -> None: # ... ``` -------------------------------- ### Combine Named and _KWARGS Arguments in icontract Conditions Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst Illustrates how to define an `icontract.require` condition that simultaneously refers to both explicitly named arguments (e.g., `x`) and variable keyword arguments accessed via `_KWARGS`. This allows for complex contract logic involving both types of function inputs. ```Python @icontract.require(lambda x, _KWARGS: x < _KWARGS["y"]) def function_c(x: int, **kwargs) -> int: return 123 ``` -------------------------------- ### Using Walrus Operator for Intermediate Variables in Contracts Source: https://github.com/parquery/icontract/blob/master/docs/source/recipes.rst Illustrates the use of Python's assignment expression (walrus operator, `:=`) within complex contract conditions. This allows for the introduction of intermediate variables, making long and intricate conditions more readable and manageable by breaking them down into smaller, reusable parts. ```python @ensure( lambda result: all( ( center := len(line) // 2, line[:center] == line[center + 1:][::-1] if len(line) % 2 == 1 else line[:center] == line[center:][::-1] )[1] for line in result ), "Horizontal symmetry" ) def draw(width: int, height: int) -> Lines: """Draw the pattern of the size ``width`` x ``height`` and return the text lines.""" ... ``` -------------------------------- ### Define icontract.require with Exception Class Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst Illustrates specifying an exception class (e.g., `ValueError`) directly to the `error` argument of `icontract.require`. When the contract is violated, an instance of the specified exception class is raised, with `icontract` automatically generating a default error message. ```Python @icontract.require(lambda x: x > 0, error=ValueError) def some_func(x: int) -> int: return 123 ``` -------------------------------- ### Serialize / Deserialize Pair with Contracts Source: https://github.com/parquery/icontract/blob/master/docs/source/recipes.rst Demonstrates how to use `icontract`'s `@ensure` decorator to define post-conditions for serialization and deserialization functions. The contract ensures that tokenizing text and then converting tokens back to text yields the original input, establishing a clear relationship between the pair of functions. This pattern is particularly useful for auto-testing tools. ```python @ensure( lambda text, result: tokens_to_text(result) == text # type: ignore ) def tokenize(text: str) -> List[Token]: ... @ensure(lambda tokens, result: tokens == tokenize(result)) def tokens_to_text(tokens: Sequence[Token]) -> str: ... ``` -------------------------------- ### Apply icontract to Functions Accepting Only _KWARGS Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst Shows how to apply an `icontract.require` condition using `_KWARGS` to a function that exclusively accepts variable keyword arguments (e.g., `def function_d(**kwargs):`). The contract can then validate specific keyword arguments passed to such a function. ```Python @icontract.require(lambda _KWARGS: _KWARGS["x"] > 0) def function_d(**kwargs) -> int: return 123 ``` -------------------------------- ### Modeling Exclusive Properties with Python's XOR Operator Source: https://github.com/parquery/icontract/blob/master/docs/source/recipes.rst Demonstrates how Python's exclusive OR (`^`) operator can be directly used within contract conditions to model exclusive properties. This ensures that only one of two conditions is true, such as movement in either the x-direction or the y-direction, but not both simultaneously. ```python @ensure( lambda pos, result: all( (next_pos.x == pos.x and next_pos.y != pos.y) ^ (next_pos.x != pos.x and next_pos.y == pos.y) for next_pos in result ), "Next is either in x- or in y-direction" ) def list_next_positions(pos: Position) -> Sequence[Position]: """List all the possible next positions based on the current position ``pos``.""" ... ``` -------------------------------- ### Python Invariant Violation on Initialization Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst Demonstrates an `icontract` invariant violation when an instance attribute is initialized to an invalid value within the `__init__` method. The invariant check fails immediately after object creation, raising a `ViolationError`. ```Python >>> @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 , line 1 in : self.x > 0: self was an instance of SomeClass self.x was -1 ``` -------------------------------- ### API Reference: icontract.ViolationError Class Source: https://github.com/parquery/icontract/blob/master/docs/source/api.rst Documents the `ViolationError` class from the `icontract` library, which is the exception raised when a contract (precondition, postcondition, or invariant) is violated. ```APIDOC icontract.ViolationError: Type: Class Description: Exception raised when a contract is violated. ``` -------------------------------- ### API Reference: icontract.invariant Class Source: https://github.com/parquery/icontract/blob/master/docs/source/api.rst Documents the `invariant` class from the `icontract` library, used for defining class invariants that must hold true before and after method execution. It includes its constructor and callable interface. ```APIDOC icontract.invariant: Type: Class Description: Represents a class invariant in design-by-contract. Methods: __init__(): Description: Initializes the invariant instance. __call__(): Description: Executes the invariant check. ``` -------------------------------- ### API Reference: icontract.InvariantCheckEvent Class Source: https://github.com/parquery/icontract/blob/master/docs/source/api.rst Documents the `InvariantCheckEvent` class from the `icontract` library, likely used for logging or handling events related to invariant checks. ```APIDOC icontract.InvariantCheckEvent: Type: Class Description: Event class related to invariant checks. ``` -------------------------------- ### Defining and Enforcing Function Postconditions with icontract.ensure Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst Illustrates the application of the `@icontract.ensure` decorator for defining postconditions. The `result` parameter allows checking the function's return value against its inputs, ensuring the function's output meets specified criteria. Violations raise `icontract.errors.ViolationError`. ```Python @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 , line 1 in : # result > x: # result was 5 # x was 10 # y was 5 ``` -------------------------------- ### Handle Custom-Named Variable Keyword Arguments with _KWARGS Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst Demonstrates that the `_KWARGS` special argument in `icontract.require` correctly captures variable keyword arguments even when the function defines them with a non-standard parameter name (e.g., `**parameters` instead of `**kwargs`). This ensures consistent contract validation regardless of naming conventions. ```Python @icontract.require(lambda _KWARGS: _KWARGS["x"] > 0) def function_e(**parameters) -> int: return 123 ``` -------------------------------- ### Python Contract for Non-Consecutive (Holes) Ranges Source: https://github.com/parquery/icontract/blob/master/docs/source/recipes.rst Shows a modification to the postcondition for token ranges, allowing 'holes' or gaps between consecutive tokens. By changing the equality check to a less-than comparison, the contract permits non-overlapping but non-adjacent ranges. ```python token1.end < token2.start ``` -------------------------------- ### Use _KWARGS for Variable Keyword Arguments in icontract Source: https://github.com/parquery/icontract/blob/master/docs/source/usage.rst Demonstrates the use of the special `_KWARGS` argument in an `icontract.require` condition to access all keyword arguments passed to the decorated function. This enables contracts to validate keyword arguments by their name, regardless of whether the function explicitly defines `**kwargs`. ```Python @icontract.require(lambda _KWARGS: _KWARGS["x"] > 0) def function_b(x: int) -> int: return 123 ``` -------------------------------- ### Assert All Keys in a Collection are Sorted Strings Source: https://github.com/parquery/icontract/blob/master/docs/source/recipes.rst This snippet demonstrates an assertion that checks if every string `key` in the `TO_NUMBER` collection is already sorted alphabetically. It uses a generator expression with `all()` to efficiently verify this condition across all elements. This pattern is useful for validating properties of string-based data. ```python assert all("".join(sorted(key)) == key for key in TO_NUMBER) ```