python_api.py


Overview

The [python_api.py](/projects/286/67218) file provides a sophisticated utility to perform approximate comparisons between numeric values, sequences, mappings, and numpy arrays. Its main feature is the [approx()](/projects/286/67332) function, which enables intuitive and flexible tolerance-based equality checks, primarily useful in testing scenarios where floating-point precision issues occur. This utility supports:

The module is designed to integrate seamlessly with testing frameworks (such as pytest) to simplify assertions involving floating-point and numeric data structures.


Class and Function Documentation

1. approx(expected, rel=None, abs=None, nan_ok=False) -> ApproxBase

**Purpose:** Factory function that returns an appropriate `ApproxBase` subclass instance to compare the `expected` value to an actual value approximately within specified tolerances.

**Parameters:**

**Returns:**

**Usage Example:**

from python_api import approx

assert 0.1 + 0.2 == approx(0.3)
assert [0.1, 0.2] == approx([0.1, 0.2])
assert {'a': 1.0} == approx({'a': 1.0})

2. Class ApproxBase

**Purpose:** Abstract base class providing the foundational interface and utilities for approximate comparisons. It is subclassed to handle various data types (scalars, sequences, mappings, numpy arrays).

**Key Attributes:**

**Key Methods:**

**Notes:**


3. Class ApproxScalar(ApproxBase)

**Purpose:** Handles approximate comparison of single numeric scalar values.

**Key Attributes:**

**Key Methods:**

**Usage Example:**

a = ApproxScalar(1.0)
print(a)  # Output: "1.0 ± 1e-06"
assert a == 1.0000005

4. Class ApproxDecimal(ApproxScalar)

**Purpose:** Specialized subclass of `ApproxScalar` for `decimal.Decimal` types, using decimal-based tolerances.

**Key Differences:**


5. Class ApproxSequenceLike(ApproxBase)

**Purpose:** Handles approximate comparison for ordered sequences (lists, tuples, or sequence-like objects).

**Key Methods:**

**Type Checking:** Raises a `TypeError` if nested sequences are detected (nested data structures not supported).


6. Class ApproxMapping(ApproxBase)

**Purpose:** Handles approximate comparison of mappings/dictionaries where values are numeric.

**Key Methods:**

**Type Checking:** Raises a `TypeError` if nested dictionaries are detected.


7. Class ApproxNumpy(ApproxBase)

**Purpose:** Specialized handler for numpy arrays, performing element-wise approximate comparisons with shape validation.

**Key Methods:**

**Implementation Detail:**


8. Helper Functions


Important Implementation Details and Algorithms


Interaction with Other System Components


Visual Diagram

classDiagram
    class ApproxBase {
        - expected
        - rel
        - abs
        - nan_ok
        + __eq__(actual)
        + __ne__(actual)
        + __bool__()
        + _approx_scalar(x)
        + _yield_comparisons(actual)
        + _check_type()
        + _repr_compare(other_side)
    }

    class ApproxScalar {
        + DEFAULT_ABSOLUTE_TOLERANCE = 1e-12
        + DEFAULT_RELATIVE_TOLERANCE = 1e-6
        + tolerance
        + __repr__()
        + __eq__(actual)
    }

    class ApproxDecimal {
        + DEFAULT_ABSOLUTE_TOLERANCE = Decimal("1e-12")
        + DEFAULT_RELATIVE_TOLERANCE = Decimal("1e-6")
        + __repr__()
    }

    class ApproxSequenceLike {
        + __repr__()
        + _repr_compare(other_side)
        + _yield_comparisons(actual)
        + _check_type()
    }

    class ApproxMapping {
        + __repr__()
        + _repr_compare(other_side)
        + _yield_comparisons(actual)
        + _check_type()
    }

    class ApproxNumpy {
        + __repr__()
        + _repr_compare(other_side)
        + _yield_comparisons(actual)
        + __eq__(actual)
    }

    ApproxScalar --|> ApproxBase
    ApproxDecimal --|> ApproxScalar
    ApproxSequenceLike --|> ApproxBase
    ApproxMapping --|> ApproxBase
    ApproxNumpy --|> ApproxBase

Summary

The [python_api.py](/projects/286/67218) file provides the `approx` mechanism for approximate equality checks essential in floating-point testing. It supports a variety of data types and structures, with configurable tolerances and detailed diagnostic messages for mismatches. Its design ensures extensibility, numpy compatibility, and safe usage patterns, making it a robust tool for numerical software testing.