Skip to content

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

Closed
@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

Activity

RonnyPfannschmidt

RonnyPfannschmidt commented on Jun 17, 2025

@RonnyPfannschmidt
Member

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

coder-aditi commented on Jun 18, 2025

@coder-aditi
Contributor

Hello @RonnyPfannschmidt , understanding the issue, I committed a fix, please review it and let me know your thoughts or any changes required.

coder-aditi

coder-aditi commented on Jun 18, 2025

@coder-aditi
Contributor

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

added a commit that references this issue on Jun 22, 2025
111685c
added a commit that references this issue on Jun 22, 2025
f74629e
added a commit that references this issue on Jun 22, 2025
7b21af1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Participants

      @RonnyPfannschmidt@rishid@coder-aditi

      Issue actions

        pytest.approx(Decimal(...)) Causes decimal.FloatOperation in __repr__ (pytest 8.4.0+) · Issue #13530 · pytest-dev/pytest