Closed
Description
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
Labels
No labels
Activity
RonnyPfannschmidt commentedon Jun 17, 2025
Thanks for the details
We where completely unaware
This needs a unittests that triggers it locally
I suspect it was missed before in the general error case and the referred change made it manifest
Would you like to try your hand in contributing a gix as you seem to work with the details in more depth than we
coder-aditi commentedon Jun 18, 2025
Hello @RonnyPfannschmidt , understanding the issue, I committed a fix, please review it and let me know your thoughts or any changes required.
coder-aditi commentedon Jun 18, 2025
Hello @RonnyPfannschmidt , @nicoddemus , I made the necessary changes you guys suggested and committed in a new branch (was facing some branch conflicts, please have a look
PR -> #13543
Fix `approx` usage with `decimal.FloatOperation` trap set (#13543)
Fix `approx` usage with `decimal.FloatOperation` trap set (#13543)
Fix `approx` usage with `decimal.FloatOperation` trap set (#13543) (#…