Skip to content

pytest.approx(Decimal(...)) Causes decimal.FloatOperation in __repr__ (pytest 8.4.0+) #13530

@rishid

Description

@rishid

pytest.approx() with decimal.Decimal objects triggers a decimal.FloatOperation error when the ApproxDecimal object's repr method is called (e.g., during print() or assertion formatting).

This happens because ApproxDecimal.repr compares its Decimal tolerance with hardcoded float literals (like 1e-3, 1e3). When the decimal context traps FloatOperations (to maintain Decimal precision), these implicit float-Decimal comparisons raise an error.

This issue started with pytest version 8.4.0 and seems related to changes from Issue #13010.

Pytest 8.4.0
Python 3.13.2
Ubuntu 24.04 LTS

# test_decimal_approx.py
import decimal

import pytest

decimal.getcontext().traps[decimal.FloatOperation] = True


def test_decimal_approx_repr_issue():
    """Reproduces the decimal.FloatOperation error from pytest.approx(Decimal)'s repr."""
    approx_obj = pytest.approx(decimal.Decimal("2.60"))
    print(f"Attempting to represent pytest.approx(Decimal): {approx_obj}")  # Triggers the bug
    assert decimal.Decimal("2.600001") == approx_obj


# You can run this test with:
# python -m pytest test_decimal_approx.py

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions