### Example for Raising Exceptions with deal.example Source: https://github.com/life4/deal/blob/master/docs/details/docs.md Demonstrate exception raising in examples using `deal.example` in conjunction with `deal.catch`. This setup ensures that the specified exception is caught and compared. ```python @deal.example(lambda: deal.catch(div, 4, 0) is ZeroDivisionError) @deal.raises(ZeroDivisionError) @deal.reason(ZeroDivisionError, lambda x: x == 0) def div(x, y): return x / y ``` -------------------------------- ### Install Deal with all extras Source: https://context7.com/life4/deal/llms.txt Install Deal with optional extras like linter and hypothesis support. For zero-dependency runtime only, use 'pip install deal'. ```bash python3 -m pip install 'deal[all]' ``` ```bash python3 -m pip install deal ``` -------------------------------- ### Index Of Example Source: https://github.com/life4/deal/blob/master/docs/details/examples.md Demonstrates the 'index_of' functionality. No specific setup or constraints mentioned. ```python import deal def index_of(): return deal.index_of([1, 2, 3, 4, 5], 3) ``` -------------------------------- ### Choice Example Source: https://github.com/life4/deal/blob/master/docs/details/examples.md Demonstrates the 'choice' functionality. No specific setup or constraints mentioned. ```python import deal def choice(): return deal.choice( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", ) ``` -------------------------------- ### Provide Testable Examples with deal.example Source: https://github.com/life4/deal/blob/master/docs/details/docs.md Use the `deal.example` decorator to add executable examples to functions. These examples are run during tests and checked by linters, but not at runtime. The example must return True to be valid. ```python @deal.example(lambda: double(3) == 6) def double(x): return x * 2 ``` -------------------------------- ### Inline Usage Examples with deal.example Source: https://context7.com/life4/deal/llms.txt Demonstrates how to attach inline usage examples to functions using `deal.example`. These examples are verified by tests and linters but not enforced at runtime. `deal.catch` can be used to specify expected exceptions. ```python import deal @deal.example(lambda: add(2, 3) == 5) @deal.example(lambda: add(-1, 1) == 0) @deal.pure def add(a: int, b: int) -> int: return a + b # Using deal.catch to demonstrate expected exceptions: @deal.example(lambda: deal.catch(divide, 10, 0) is ZeroDivisionError) @deal.example(lambda: divide(10, 2) == 5.0) @deal.raises(ZeroDivisionError) @deal.reason(ZeroDivisionError, lambda x, y: y == 0) def divide(x: float, y: float) -> float: return x / y ``` -------------------------------- ### Count Example Source: https://github.com/life4/deal/blob/master/docs/details/examples.md Demonstrates the 'count' functionality. No specific setup or constraints mentioned. ```python import deal def count(): return deal.count([1, 2, 3, 4, 5], 3) ``` -------------------------------- ### Division Example Source: https://github.com/life4/deal/blob/master/docs/details/examples.md Shows the 'div' functionality. No specific setup or constraints mentioned. ```python import deal def div(): return deal.div(10, 2) ``` -------------------------------- ### Install Deal with all features Source: https://github.com/life4/deal/blob/master/README.md Command to install the deal library with all optional dependencies, including analysis tools. This command is executed in the terminal. ```bash python3 -m pip install --user 'deal[all]' ``` -------------------------------- ### Concatenation Example Source: https://github.com/life4/deal/blob/master/docs/details/examples.md Illustrates the 'concat' functionality. No specific setup or constraints mentioned. ```python import deal def concat(): return deal.concat("a", "b", "c") ``` -------------------------------- ### Format String Example with Linter Output Source: https://github.com/life4/deal/blob/master/docs/details/examples.md Shows string formatting examples and associated linter errors for incorrect argument counts or types. The linter flags issues with missing arguments, too many arguments, and incorrect type matching. ```python import deal def format_example(): print(format('{:s}')) # not enough args print(format('{:s}', 'a', 'b')) # too many args print(format('{:d}', 'a')) # bad type ``` -------------------------------- ### Install flake8 and Deal Source: https://github.com/life4/deal/blob/master/docs/basic/linter.md Install flake8 and deal using pip. This enables the built-in flake8 plugin for Deal. ```bash python3 -m pip install --user flake8 deal ``` -------------------------------- ### Python DbC Example Source: https://github.com/life4/deal/blob/master/README.md Demonstrates basic usage of deal decorators for postconditions and purity, and how to generate test cases. Ensure the 'deal' library is imported. ```python # the result is always non-negative @deal.post(lambda result: result >= 0) # the function has no side-effects @deal.pure def count(items: List[str], item: str) -> int: return items.count(item) # generate test function test_count = deal.cases(count) ``` -------------------------------- ### Install CrossHair Source: https://github.com/life4/deal/blob/master/docs/basic/crosshair.md Install CrossHair using pip. This command should be run with root privileges or using the --user flag. ```bash python3 -m pip install --user crosshair-tool ``` -------------------------------- ### Sphinx Integration Example Source: https://github.com/life4/deal/blob/master/docs/details/examples.md Demonstrates how to integrate Deal with Sphinx for automatic documentation generation. This involves configuring Sphinx extensions and using directives like 'autofunction'. ```python import deal # In docs/conf.py extensions = ['sphinx.ext.autodoc'] def setup(app): deal.autodoc(app) ``` ```rst .. autofunction:: examples.sphinx.example ``` ```python import deal @deal.module() def example(): pass ``` -------------------------------- ### Using Hypothesis for Fuzzing Source: https://github.com/life4/deal/blob/master/docs/details/examples.md Demonstrates fuzzing a function using the Hypothesis library. Requires Hypothesis to be installed. ```python import deal from hypothesis import given from hypothesis.strategies import characters @deal.fuzz(characters(min_codepoint=97, max_codepoint=122)) def fuzz(x): return x def main(): return given(fuzz) ``` -------------------------------- ### Fuzzing with Atheris Source: https://github.com/life4/deal/blob/master/docs/details/examples.md Example of fuzzing a function using the Atheris library. Requires Atheris to be installed. ```python import deal import atheris @deal.fuzz( lambda: deal.choice("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"), ) def fuzz(x): return x def main(): atheris.setup(None) atheris. fuzz(fuzz) ``` -------------------------------- ### Fuzzing with PythonFuzz Source: https://github.com/life4/deal/blob/master/docs/details/examples.md Example of fuzzing a function using the PythonFuzz library. Requires PythonFuzz to be installed. ```python import deal import pythonfuzz @deal.fuzz( lambda: deal.choice("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"), ) def fuzz(x): return x def main(): pythonfuzz.main() ``` -------------------------------- ### Minimum Value Example Source: https://github.com/life4/deal/blob/master/docs/details/examples.md Illustrates finding the minimum value in a list. The linter output indicates that passing an empty list to 'my_min' will result in a pre-contract error. ```python import deal @deal.ensure(lambda result: result >= 0) def my_min(lst): return min(lst) ``` -------------------------------- ### Module Initialization Purity Source: https://github.com/life4/deal/blob/master/docs/details/recipes.md Ensure module initialization is pure by deferring complex operations and using lazy loading. This example demonstrates marking the module load as pure. ```python import deal deal.module_load(deal.pure) ``` -------------------------------- ### Factorial calculation using dispatch Source: https://github.com/life4/deal/blob/master/docs/details/dispatch.md Example of recursively calculating factorial using `deal.dispatch`, similar to Elixir's pattern matching. ```elixir defmodule Math do @spec fac(integer) :: integer @doc """ Calculate factorial of the given number. """ def fac(0), do: 1 def fac(n) when n > 0, do: n * fac(n - 1) end Math.fac(5) # 120 Math.fac(-1) # FunctionClauseError ``` ```python import deal @deal.dispatch def fac(n: int) -> int: """Calculate factorial of the given number. """ raise NotImplementedError @fac.register @deal.pre(lambda n: n == 0) def _(n): return 1 @fac.register @deal.pre(lambda n: n > 0) def _(n): return n * fac(n - 1) fac(5) # 120 fac(-1) # NoMatchError ``` -------------------------------- ### Run flake8 for Deal linting Source: https://github.com/life4/deal/blob/master/docs/basic/linter.md Execute flake8 to perform static checks on your code. Deal's plugin will be automatically discovered if installed in the same environment. ```bash python3 -m flake8 ``` -------------------------------- ### Run Deal linter with JSON output Source: https://github.com/life4/deal/blob/master/docs/basic/linter.md Execute the Deal linter with the `--json` option to get a compact JSON output. This is useful for integrating with other tools like jq. ```bash python3 -m deal lint --json ``` -------------------------------- ### Configure Sphinx Autodoc with Deal Source: https://github.com/life4/deal/blob/master/docs/details/docs.md Integrate Deal with Sphinx's autodoc extension by adding `deal.autodoc` to your Sphinx setup. This automatically includes contract documentation in generated docs. ```python import deal extensions = ['sphinx.ext.autodoc'] def setup(app): deal.autodoc(app) ``` -------------------------------- ### Partial execution of contracts for linting Source: https://github.com/life4/deal/blob/master/docs/basic/linter.md Demonstrates how the Deal linter can partially execute `pre` and `post` contracts. This example defines a function with a post-condition that is violated, triggering a DEL012 error. ```python import deal @deal.post(lambda r: r != 0) def f(): return 0 ``` -------------------------------- ### Fuzzing with Atheris Source: https://github.com/life4/deal/blob/master/docs/details/tests.md Integrate deal.cases with Atheris for fuzz testing. Ensure Atheris is installed and the target function is available. ```python import atheris test = deal.cases(div) atheris.Setup([], test) atheris.Fuzz() ``` -------------------------------- ### Fuzzing with PythonFuzz Source: https://github.com/life4/deal/blob/master/docs/details/tests.md Integrate deal.cases with PythonFuzz for fuzz testing. Ensure PythonFuzz is installed and the target function is available. ```python from pythonfuzz.main import PythonFuzz test = deal.cases(div) PythonFuzz(test)() ``` -------------------------------- ### Simple Precondition for Division Source: https://github.com/life4/deal/blob/master/docs/details/recipes.md Use a simple lambda for contracts when a function has few short arguments. This example enforces that the divisor is not zero. ```python import deal @deal.pre(lambda left, right: right != 0) def div(left: float, right: float) -> float: return left / right ``` -------------------------------- ### Execute Pytest Command Source: https://github.com/life4/deal/blob/master/docs/basic/motivation.md This command runs the pytest test suite. Ensure you have pytest installed and the test file saved as `cat.py`. ```bash pytest cat.py ``` -------------------------------- ### Bank Transfer with Deal Contracts Source: https://context7.com/life4/deal/llms.txt A contract-driven implementation of a bank transfer function using various Deal decorators (pre, post, ensure, raises, has, reason, cases). This example demonstrates how to enforce business logic and invariants. ```python """ Contract-driven implementation of a bank transfer function. Demonstrates pre, post, ensure, raises, has, reason, and cases. """ import deal from typing import Dict transfer_contract = deal.chain( deal.pre(lambda src, dst, amount, accounts: src in accounts and dst in accounts, message='both accounts must exist'), deal.pre(lambda src, dst, amount, accounts: src != dst, message='cannot transfer to same account'), deal.pre(lambda src, dst, amount, accounts: amount > 0, message='amount must be positive'), deal.ensure(lambda src, dst, amount, accounts, result: result[src] == accounts[src] - amount, message='source balance must decrease by amount'), deal.ensure(lambda src, dst, amount, accounts, result: result[dst] == accounts[dst] + amount, message='destination balance must increase by amount'), deal.ensure(lambda src, dst, amount, accounts, result: sum(result.values()) == sum(accounts.values()), message='total money must be conserved'), deal.raises(ValueError), deal.reason(ValueError, lambda src, dst, amount, accounts: accounts[src] < amount, message='insufficient funds'), deal.has(), # no side-effects ) @transfer_contract def transfer( src: str, dst: str, amount: float, accounts: Dict[str, float], ) -> Dict[str, float]: if accounts[src] < amount: raise ValueError('Insufficient funds') result = dict(accounts) result[src] -= amount result[dst] += amount return result # --- Usage --- accounts = {'alice': 1000.0, 'bob': 500.0} result = transfer('alice', 'bob', 200.0, accounts) # {'alice': 800.0, 'bob': 700.0} transfer('alice', 'bob', 5000.0, accounts) # ValueError: Insufficient funds transfer('alice', 'alice', 100.0, accounts) # PreContractError: cannot transfer to same account # Auto-generate property-based tests (requires type annotations): # test_transfer = deal.cases(transfer) ``` -------------------------------- ### Complex Precondition with Default Value Source: https://github.com/life4/deal/blob/master/docs/details/recipes.md For functions with default arguments or more complex logic, use a simplified signature for contracts. This example handles ZeroDivisionError by returning a default value if provided. ```python import deal @deal.pre(lambda _: _.default is not None or _.right != 0) def div(left: float, right: float, default: float = None) -> float: try: return left / right except ZeroDivisionError: if default is not None: return default raise ``` -------------------------------- ### Define Contracts for index_of Function Source: https://github.com/life4/deal/blob/master/docs/basic/tests.md Create a chain of contracts using `deal.chain` to specify requirements for the `index_of` function, including result range, element matching, first match guarantee, and exception handling for missing elements. This example also includes a `deal.has()` contract to ensure no side effects. ```python from typing import List, NoReturn import deal contract_for_index_of = deal.chain( deal.post(lambda result: result >= 0), deal.ensure(lambda items, item, result: result < len(items)), deal.ensure( lambda items, item, result: items[result] == item, message='invalid match', ), deal.ensure( lambda items, item, result: item not in items[:result], message='not the first match', ), deal.raises(LookupError), deal.reason(LookupError, lambda items, item: item not in items), deal.has(), ) ``` -------------------------------- ### Enforce Module Contracts with `deal.module_load` Source: https://github.com/life4/deal/blob/master/docs/details/module_load.md Use `deal.module_load` within a module to specify contracts that must be satisfied upon loading. Only contracts from the `deal` library without arguments are supported. This example demonstrates loading the `deal.pure` contract, and a subsequent print statement is commented to indicate where a `deal.SilentContractError` would be raised if the contract is violated. ```python import deal import something_else deal.module_load(deal.pure) something = 1 print(1) # contract violation! deal.SilentContractError will be raised ``` -------------------------------- ### Reading configuration files with dispatch Source: https://github.com/life4/deal/blob/master/docs/details/dispatch.md Demonstrates using `deal.dispatch` to handle different configuration file formats based on file extensions. ```python from pathlib import Path # Assume Config is defined elsewhere # class Config: pass @deal.dispatch def read_config(path: Path) -> 'Config': raise NotImplementedError @read_config.register @deal.pre(lambda path: path.suffix == '.json') def read_json(path): # Implementation for JSON pass @read_config.register @deal.pre(lambda path: path.suffix in {'.yml', '.yaml'}) def read_yaml(path): # Implementation for YAML pass ``` -------------------------------- ### Run Formal Verification Source: https://github.com/life4/deal/blob/master/docs/basic/verification.md Execute the Deal formal verifier on your project. Ensure your code adheres to the prerequisites for verification. ```bash python3 -m deal prove project/ ``` -------------------------------- ### Generate Contracts with CLI Source: https://github.com/life4/deal/blob/master/docs/details/contracts.md Use the `deal decorate` CLI command to automatically generate contracts for your project. It runs the linter and adds supported contracts, but generated code should be reviewed for correctness. ```bash python3 -m deal decorate my_project/ ``` -------------------------------- ### Deal CLI: Lint Command Source: https://context7.com/life4/deal/llms.txt Use the 'deal lint' command to perform static analysis on your project. It can output results in JSON format for further processing. ```bash # Run the deal linter on your project python3 -m deal lint my_project/ # Output as JSON (pipe to jq for formatting) python3 -m deal lint --json my_project/ | jq . # Use the flake8 integration instead: python3 -m flake8 my_project/ ``` -------------------------------- ### Type Checking with PySchemes Source: https://github.com/life4/deal/blob/master/docs/details/recipes.md Integrate type checking into contracts using PySchemes for dynamic validation. This example ensures string arguments for concatenation. ```python import deal from pyschemes import Scheme @deal.pre(Scheme(dict(left=str, right=str))) def concat(left, right): return left + right concat('ab', 'cd') # 'abcd' concat(1, 2) # PreContractError: at key 'left' (expected type: 'str', got 'int') ``` -------------------------------- ### Define a Simple String Concatenation Function Source: https://github.com/life4/deal/blob/master/docs/basic/motivation.md This is a basic Python function to concatenate two strings. It serves as a simple example for demonstrating testing techniques. ```python def cat(left, right): """Concatenate two given strings. """ return left + right ``` -------------------------------- ### Run Deal linter CLI Source: https://github.com/life4/deal/blob/master/docs/basic/linter.md Use the built-in CLI command from Deal to lint your Python files. This command provides colored output by default. ```bash python3 -m deal lint ``` -------------------------------- ### Test Command Source: https://github.com/life4/deal/blob/master/docs/details/cli.md The `test` command is used to execute tests within the Deal project. ```APIDOC ## test ### Description Executes the test suite for the project. ### Method CLI Command ### Endpoint test ### Parameters This command does not accept any parameters directly. Refer to the underlying `deal._cli._test.TestCommand` for specific behavior. ``` -------------------------------- ### Precondition-Based Dispatch with deal.dispatch Source: https://context7.com/life4/deal/llms.txt Illustrates how `deal.dispatch` can be used to combine multiple function implementations. The first implementation whose preconditions are met is executed. Raises `NoMatchError` if no implementation matches. ```python import deal from pathlib import Path @deal.dispatch def read_config(path: Path) -> dict: """Read configuration from a file.""" raise NotImplementedError @read_config.register @deal.pre(lambda path: path.suffix == '.json') def read_json(path: Path) -> dict: import json return json.loads(path.read_text()) @read_config.register @deal.pre(lambda path: path.suffix in {'.yml', '.yaml'}) def read_yaml(path: Path) -> dict: import yaml return yaml.safe_load(path.read_text()) @read_config.register def read_default(path: Path) -> dict: raise ValueError(f'Unsupported format: {path.suffix}') read_config(Path('config.json')) # dispatches to read_json read_config(Path('config.yaml')) # dispatches to read_yaml # Recursive factorial example using dispatch: @deal.dispatch def factorial(n: int) -> int: raise NotImplementedError @factorial.register @deal.pre(lambda n: n == 0) def _(n: int) -> int: return 1 @factorial.register @deal.pre(lambda n: n > 0) def _(n: int) -> int: return n * factorial(n - 1) factorial(5) # 120 factorial(-1) # NoMatchError ``` -------------------------------- ### Run Deal Tests via CLI Source: https://github.com/life4/deal/blob/master/docs/basic/tests.md The `deal test` command can automatically find and run tests for `deal.pure` and `@deal.has()` wrapped functions in specified Python files. It also reports code coverage achieved by the generated test inputs. ```bash python3 -m deal test project/*.py ``` -------------------------------- ### Linter output for contract violation Source: https://github.com/life4/deal/blob/master/docs/basic/linter.md Example output from the Deal linter when a contract violation is detected. It shows the file, line number, error code (DEL012), and a message indicating the post-contract error. ```bash $ python3 -m deal lint tmp.py tmp.py 6:11 DEL012 post contract error (0) return 0 ``` -------------------------------- ### Prove Command Source: https://github.com/life4/deal/blob/master/docs/details/cli.md The `prove` command is likely used for formal verification or proof generation within the Deal project. ```APIDOC ## prove ### Description Executes the proving mechanism for formal verification. ### Method CLI Command ### Endpoint prove ### Parameters This command does not accept any parameters directly. Refer to the underlying `deal._cli._prove.ProveCommand` for specific behavior. ``` -------------------------------- ### Dispatching function with preconditions Source: https://github.com/life4/deal/blob/master/docs/details/dispatch.md Define a base function and register implementations with preconditions. If no implementation matches, `NoMatchError` is raised. ```python import deal @deal.dispatch def age2stage(age: int) -> str: raise NotImplementedError @age2stage.register @deal.pre(lambda age: age < 12) def _(age: int) -> str: return 'kid' @age2stage.register @deal.pre(lambda age: age < 18) def _(age: int) -> str: return 'teen' age2stage(10) # 'kid' age2stage(14) # 'teen' ``` ```python age2stage(20) # NoMatchError: expected age < 12 (where age=20); expected age < 18 (where age=20) ``` ```python @age2stage.register def _(age: int) -> str: return 'adult' age2stage(20) # 'adult' ``` -------------------------------- ### Test String Concatenation Properties with Pytest Source: https://github.com/life4/deal/blob/master/docs/basic/motivation.md Instead of checking exact results, this test verifies properties of the concatenated string: it starts with the left string, ends with the right string, and its length is the sum of the input lengths. This approach is more robust for complex functions. ```python @pytest.mark.parametrize('left, right', [ ('a', 'b'), ('', ''), ('', 'b'), ('a', ''), ('text', 'check'), ]) def test_cat(left, right): result = cat(left=left, right=right) assert result.startswith(left) assert result.endswith(right) assert len(result) == len(left) + len(right) ``` -------------------------------- ### Automatic Test Discovery with Pytest Source: https://context7.com/life4/deal/llms.txt Demonstrates how pytest can automatically discover and run tests defined using the `deal.cases` decorator. Extended form shows custom assertions and fixture usage. ```python test_index_of = deal.cases(index_of) # Extended form with fixtures and custom assertions: @deal.cases(index_of, count=200) def test_index_of_extended(case: deal.TestCase) -> None: result = case() # case.kwargs contains the generated arguments if not isinstance(result, type(None)): items = case.kwargs['items'] item = case.kwargs['item'] assert items[result] == item # Run manually: test_index_of() # Fix specific arguments to narrow testing: fixed_cases = deal.cases(index_of, kwargs={'item': 42}, count=50) fixed_cases() ``` -------------------------------- ### Deal CLI: Decorate Command Source: https://context7.com/life4/deal/llms.txt Use the 'deal decorate' command to automatically add contracts like @deal.has, @deal.raises, and @deal.safe, which are inferred by the linter. ```bash # Automatically add @deal.has, @deal.raises, @deal.safe contracts inferred by linter python3 -m deal decorate my_project/ ``` -------------------------------- ### Deal CLI: Prove Command Source: https://context7.com/life4/deal/llms.txt The 'deal prove' command performs formal verification of contracts using the Z3 theorem prover. It can report violations, such as a post-contract being provably violated. ```bash # Formally verify contracts using Z3 theorem prover python3 -m deal prove my_project/ # Example: a function whose post-contract is provably violated # @deal.post(lambda r: r != 0) # def f(): return 0 # → deal prove reports: post contract error (0) ``` -------------------------------- ### Generating Stubs with Deal Source: https://github.com/life4/deal/blob/master/docs/details/stubs.md Use the `deal stub` command to generate stub files for a Python file. These stubs are then used by the linter to detect contracts in third-party libraries. ```bash python3 -m deal stub /path/to/a/file.py ``` -------------------------------- ### Create and Run Tests for index_of Source: https://github.com/life4/deal/blob/master/docs/basic/tests.md Generate test cases for the `index_of` function using `deal.cases` with a specified count. The test function `test_index_of` executes each generated case and prints the result if no exception is raised, demonstrating how to test contract-driven functions and inspect results. ```python import deal from typing import List, NoReturn @deal.cases(index_of, count=1000) def test_index_of(case): result = case() if result is not NoReturn: print(f"index of {case.kwargs['item']} in {case.kwargs['items']} is {result}") ``` -------------------------------- ### Composing Contracts with deal.chain Source: https://context7.com/life4/deal/llms.txt Shows how to combine multiple contracts (preconditions, postconditions, ensures, raises, has) into a single reusable decorator using `deal.chain`. This keeps function definitions clean and contracts centralized. ```python import deal from typing import List # Define contracts separately from the function sortable_contract = deal.chain( deal.pre(lambda lst: isinstance(lst, list), message='must be a list'), deal.pre(lambda lst: len(lst) > 0, message='list must not be empty'), deal.post(lambda result: len(result) > 0), deal.ensure(lambda lst, result: len(result) == len(lst), message='length must be preserved'), deal.ensure( lambda lst, result: all(result[i] <= result[i+1] for i in range(len(result)-1)), message='result must be sorted', ), deal.raises(), # no exceptions allowed deal.has(), # no side-effects ) @sortable_contract def bubble_sort(lst: List[int]) -> List[int]: lst = lst[:] for i in range(len(lst)): for j in range(len(lst) - i - 1): if lst[j] > lst[j + 1]: lst[j], lst[j + 1] = lst[j + 1], lst[j] return lst bubble_sort([3, 1, 4, 1, 5]) # [1, 1, 3, 4, 5] bubble_sort([]) # PreContractError: list must not be empty ``` -------------------------------- ### Deal CLI: Test Command Source: https://context7.com/life4/deal/llms.txt The 'deal test' command automatically finds and tests functions decorated with @deal.pure or @deal.has(). It can show per-function coverage of generated test inputs. ```bash # Find and test all @deal.pure / @deal.has() functions python3 -m deal test my_project/*.py # Shows per-function coverage of generated test inputs ``` -------------------------------- ### Configure Mypy for Deal Plugin Source: https://github.com/life4/deal/blob/master/docs/details/contracts.md Configure `pyproject.toml` to enable the Deal plugin for Mypy. This plugin checks types for validators but does not execute contracts. Ensure Mypy version is 0.910 or higher. ```toml [tool.mypy] plugins = ["deal.mypy"] ``` -------------------------------- ### Define Function for Testing Source: https://github.com/life4/deal/blob/master/docs/basic/tests.md Functions must have type annotations and specified exceptions using `deal.raises` and preconditions with `deal.pre` before they can be tested by Deal. ```python import deal @deal.raises(ZeroDivisionError) @deal.pre(lambda a, b: a >= 0 and b >= 0) def div(a: int, b: int) -> float: return a / b ``` -------------------------------- ### Activate Deal Import Hooks Source: https://github.com/life4/deal/blob/master/docs/details/module_load.md Call `deal.activate()` once at the beginning of your application before any imports to enable Deal's contract checking mechanism. ```python import deal deal.activate() from .other import something ``` -------------------------------- ### Function Analysis with Deal Linter Source: https://github.com/life4/deal/blob/master/docs/details/stubs.md Demonstrates how the Deal linter analyzes function calls. It detects explicit contracts but may not report errors from deep within call chains without explicit contracts or stubs. ```python import deal def a(): raise ValueError @deal.raises(NameError) def b(): return a() ``` ```bash $ python3 -m deal lint tmp.py tmp.py 8:11 raises contract error (ValueError) return a() ``` ```python import deal def a(): raise ValueError def b(): return a() @deal.raises(NameError) def c(): return b() ``` -------------------------------- ### Stub Command Source: https://github.com/life4/deal/blob/master/docs/details/cli.md The `stub` command is used for creating stubs, which are often used in testing to mock dependencies. ```APIDOC ## stub ### Description Generates stubs for dependencies or components. ### Method CLI Command ### Endpoint stub ### Parameters This command does not accept any parameters directly. Refer to the underlying `deal._cli._stub.StubCommand` for specific behavior. ``` -------------------------------- ### Reason and Raises for Exceptions Source: https://github.com/life4/deal/blob/master/docs/details/recipes.md Use `@deal.reason` to specify the conditions under which an exception can occur and `@deal.raises` to declare that the exception might be raised. This helps in understanding potential error scenarios. ```python import deal @deal.reason(ZeroDivisionError, lambda a, b: b == 0) @deal.raises(ZeroDivisionError) def divide(a, b): return a / b ``` -------------------------------- ### Decorate Command Source: https://github.com/life4/deal/blob/master/docs/details/cli.md The `decorate` command is used to apply decorations to code, likely for analysis or transformation purposes. ```APIDOC ## decorate ### Description Applies decorations to the code. ### Method CLI Command ### Endpoint decorate ### Parameters This command does not accept any parameters directly. Refer to the underlying `deal._cli._decorate.DecorateCommand` for specific behavior. ``` -------------------------------- ### Enable Deal's mypy Plugin Source: https://context7.com/life4/deal/llms.txt Add 'deal.mypy' to your mypy plugins in pyproject.toml to enable type-checking for contract validators. ```toml # pyproject.toml [tool.mypy] plugins = ["deal.mypy"] ``` -------------------------------- ### Run mypy for Type Checking Source: https://context7.com/life4/deal/llms.txt Execute the mypy command to check your project for type errors, including those related to Deal contracts. ```bash mypy my_project/ ``` -------------------------------- ### Define function contracts with short signatures using Deal in Python Source: https://github.com/life4/deal/blob/master/docs/basic/motivation.md Utilize short signatures with 'deal.ensure' for more concise contract definitions. This approach simplifies the expression of function properties, making the code more readable. ```python import deal @deal.ensure(lambda _: _.result.startswith(_.left)) @deal.ensure(lambda _: _.result.endswith(_.right)) @deal.ensure(lambda _: len(_.result) == len(_.left) + len(_.right)) def cat(left: str, right: str) -> str: return left + right ``` -------------------------------- ### Generate Basic Test Cases Source: https://github.com/life4/deal/blob/master/docs/basic/tests.md Use `deal.cases` to create a test object for a function. This object can be called to run tests or used with testing frameworks like pytest. ```python test_div = deal.cases(div) ``` -------------------------------- ### Lint Command Source: https://github.com/life4/deal/blob/master/docs/details/cli.md The `lint` command is used for code linting within the Deal project. It helps maintain code quality and consistency. ```APIDOC ## lint ### Description Runs the linter to check for code style and potential issues. ### Method CLI Command ### Endpoint lint ### Parameters This command does not accept any parameters directly. Refer to the underlying `deal._cli._lint.LintCommand` for specific behavior. ``` -------------------------------- ### Define function precondition with @deal.pre Source: https://context7.com/life4/deal/llms.txt Use `@deal.pre` to validate conditions before a function executes. It raises `PreContractError` on violation. The `_` argument can be used as a container for all arguments. ```python import deal @deal.pre(lambda a, b: a >= 0 and b >= 0, message='both arguments must be non-negative') def divide(a: float, b: float) -> float: return a / b divide(10, 2) # 5.0 divide(-1, 2) # PreContractError: both arguments must be non-negative (where a=-1, b=2) # Simplified signature: use _ as a container for all arguments (useful with defaults) @deal.pre(lambda _: _.divisor != 0, message='divisor must be non-zero') def safe_div(value: float, divisor: float = 1.0) -> float: return value / divisor safe_div(10, 0) # PreContractError: divisor must be non-zero (where divisor=0, value=10) safe_div(10, 2) # 5.0 ``` -------------------------------- ### Specify Side-effect Markers Source: https://github.com/life4/deal/blob/master/docs/basic/side-effects.md Use @deal.has to declare markers like 'stdout' and 'database' for a function. Deal verifies that if a function calls another with certain markers, those markers are also declared for the calling function. ```python import deal @deal.has('stdout', 'database') def say_hello(id: int) -> None: user = get_user(id=id) print(f'Hello, {user.name}') ``` -------------------------------- ### Runtime Contract State Management Source: https://context7.com/life4/deal/llms.txt Control contract enforcement at runtime using deal.disable(), deal.enable(), and deal.reset(). Contracts are automatically disabled in optimized mode (-O). ```python import deal @deal.pre(lambda x: x > 0) def positive_only(x: int) -> int: return x * 2 positive_only(3) # 6 positive_only(-1) # PreContractError # Disable for a performance-critical section: deal.disable() positive_only(-1) # -2 (no error — contracts are off) # Re-enable: deal.enable() positive_only(-1) # PreContractError again # Restore default behavior (enabled iff __debug__ is True): deal.reset() # Permanently disable (cannot be re-enabled; must be called before any decorated imports): # deal.disable(permanent=True) # Disable syntax highlighting in error messages (CI environments): import os os.environ['NO_COLOR'] = '1' ``` -------------------------------- ### Simplified Contract Signature Source: https://github.com/life4/deal/blob/master/docs/details/contracts.md When dealing with complex function signatures, use a lambda that accepts a single '_' argument. Deal will pass a container with all function arguments to this lambda, simplifying contract definition. ```python import deal @deal.pre(lambda _: _.a + _.b > 0) def f(a, b=1): return a + b f(1) # 2 f(-2) # PreContractError: expected a + b > 0 (where a=-2, b=1) ``` -------------------------------- ### Use Custom Hypothesis Strategies with deal.cases Source: https://github.com/life4/deal/blob/master/docs/details/tests.md Integrate custom Hypothesis strategies into `deal.cases` via the `kwargs` argument to control test case generation for specific function arguments. ```python import hypothesis.strategies as st @deal.raises(ZeroDivisionError) def div(a: int, b: int) -> float: assert a >= 10 return a / b cases = deal.cases( func=div, kwargs=dict( a=st.integers(min_value=10), ), ) for case in cases: case() ``` -------------------------------- ### Chaining Preconditions with deal Source: https://github.com/life4/deal/blob/master/docs/basic/values.md Multiple @deal.pre decorators can be chained to enforce a sequence of preconditions. Contracts are resolved from top to bottom. ```python import deal @deal.pre(lambda x: x > 0) @deal.pre(lambda x: x < 10) def f(x): return x * 2 print(f(5)) # 10 # This will raise PreContractError # print(f(-1)) # This will raise PreContractError # print(f(12)) ``` -------------------------------- ### Property-Based Testing with Hypothesis Source: https://github.com/life4/deal/blob/master/docs/basic/motivation.md Leverage the Hypothesis library to automatically generate a wide range of inputs for the `cat` function. This ensures thorough testing by exploring numerous edge cases, including Unicode and special characters, that might be missed by manual test case creation. ```python import hypothesis from hypothesis import strategies @hypothesis.given(left=strategies.text(), right=strategies.text()) def test_cat(left, right): result = cat(left=left, right=right) assert result.startswith(left) assert result.endswith(right) assert len(result) == len(left) + len(right) ``` -------------------------------- ### Contract Inheritance with deal.inherit Source: https://context7.com/life4/deal/llms.txt Explains how `deal.inherit` allows subclass methods to inherit contracts from their base class, ensuring adherence to the Liskov Substitution Principle. This can be applied to specific methods or all methods of a class. ```python import deal class Shape: @deal.post(lambda r: r > 0, message='sides must be positive') @deal.raises() def get_sides(self) -> int: raise NotImplementedError # Inherit contracts on a specific method: class Triangle(Shape): @deal.inherit def get_sides(self) -> int: return 3 # OK: 3 > 0 class Point(Shape): @deal.inherit def get_sides(self) -> int: return 0 # PostContractError: sides must be positive # Inherit contracts for all methods of the class: @deal.inherit class Pentagon(Shape): def get_sides(self) -> int: return 5 Pentagon().get_sides() # 5 ``` -------------------------------- ### Inherit Contracts in Classes Source: https://github.com/life4/deal/blob/master/docs/details/contracts.md Decorate an entire class with `@deal.inherit` to make all its methods inherit contracts from base classes. This is useful for applying inheritance rules across multiple methods. ```python import deal @deal.inherit class Line(Shape): def get_sides(self): return 2 line = Line() line.get_sides() # PreContractError: expected r > 0 (where r=2) ``` -------------------------------- ### Enable/Disable Contracts in Runtime Source: https://github.com/life4/deal/blob/master/docs/basic/runtime.md Use these functions to control contract enforcement during runtime. `deal.disable()` turns off all contracts, `deal.enable()` turns them on, and `deal.reset()` restores the default behavior based on the `__debug__` flag. ```python # disable all contracts deal.disable() # enable all contracts deal.enable() # restore the default behavior # (enabled if `__debug__` is True, disabled otherwise) deal.reset() ``` -------------------------------- ### Generate test cases for functions with Deal contracts in Python Source: https://github.com/life4/deal/blob/master/docs/basic/motivation.md Use 'deal.cases' to automatically generate test cases for functions decorated with Deal contracts. This simplifies the testing process by creating inputs that satisfy or violate the defined contracts. ```python test_cat = deal.cases(cat) ``` -------------------------------- ### Deal Testing Utilities Source: https://github.com/life4/deal/blob/master/docs/details/api.md Utilities for testing Deal contracts, including test case classes. ```APIDOC ## deal.cases ### Description A class for defining and running test cases for Deal contracts. ### Members (Members are documented in the source, but specific methods are not detailed here) ### Request Example (No request example provided) ### Response (No response details provided) ``` ```APIDOC ## deal.TestCase ### Description A base class for creating custom test cases with Deal. ### Members (Members are documented in the source, but specific methods are not detailed here) ### Request Example (No request example provided) ### Response (No response details provided) ``` -------------------------------- ### Create a Pytest Test Function Source: https://github.com/life4/deal/blob/master/docs/basic/tests.md Define a test function that accepts a `deal.TestCase` object. This allows Deal to generate and run test cases for the decorated function, integrating seamlessly with pytest fixtures. ```python import deal @deal.cases(div) def test_div(case: deal.TestCase) -> None: case() ``` -------------------------------- ### Pre-Contract for Strict Mode Value Source: https://context7.com/life4/deal/llms.txt Use @deal.pre to define a pre-condition that checks if the mode is 'strict', in which case the value must be positive. If the mode is not 'strict', the implication is vacuously true. ```python import deal @deal.pre(lambda _: deal.implies(_.mode == 'strict', _.value > 0)) def process(value: int, mode: str = 'normal') -> int: return value * 2 process(-5) # -10 (mode='normal', implication vacuously true) process(-5, mode='strict') # PreContractError process(5, mode='strict') # 10 ``` -------------------------------- ### Deal Helpers Source: https://github.com/life4/deal/blob/master/docs/details/api.md Helper functions for composing and managing Deal contracts. ```APIDOC ## deal.inherit ### Description Allows contracts to inherit from other contracts. ### Method `deal.inherit` ### Parameters (No specific parameters documented in source) ### Request Example (No request example provided) ### Response (No response details provided) ``` ```APIDOC ## deal.chain ### Description Chains multiple contracts together. ### Method `deal.chain` ### Parameters (No specific parameters documented in source) ### Request Example (No request example provided) ### Response (No response details provided) ``` ```APIDOC ## deal.pure ### Description Marks a function as pure (no side-effects). ### Method `deal.pure` ### Parameters (No specific parameters documented in source) ### Request Example (No request example provided) ### Response (No response details provided) ``` ```APIDOC ## deal.safe ### Description Defines a safe version of a function that handles potential errors. ### Method `deal.safe` ### Parameters (No specific parameters documented in source) ### Request Example (No request example provided) ### Response (No response details provided) ``` ```APIDOC ## deal.implies ### Description Defines a logical implication between conditions. ### Method `deal.implies` ### Parameters (No specific parameters documented in source) ### Request Example (No request example provided) ### Response (No response details provided) ``` ```APIDOC ## deal.catch ### Description Catches and handles exceptions within a contract. ### Method `deal.catch` ### Parameters (No specific parameters documented in source) ### Request Example (No request example provided) ### Response (No response details provided) ``` -------------------------------- ### Ensure Contract for List and Result Source: https://context7.com/life4/deal/llms.txt Use @deal.ensure to specify a post-condition that must hold true if the input list is non-empty. The result must be present in the list. ```python import deal @deal.ensure(lambda items, result: deal.implies(bool(items), result in items)) def first_or_default(items: list, default=None): return items[0] if items else default first_or_default([1, 2, 3]) # 1 first_or_default([], -1) # -1 ```