Batu Lab NotesPractical developer guides

Stop assertAlmostEqual from accepting the wrong numeric tolerance

By Batu · English technical notes

A direct answer to “Stop assertAlmostEqual from accepting the wrong numeric tolerance Python” is: use delta when the requirement is an absolute difference. A places argument expresses rounding to decimal places, which can produce a different verdict from the boundary your domain actually specifies.

This fixture compares fixed measurements, 10.0000 and 10.0049. Their absolute difference is 0.0049. places=2 accepts them because the difference rounds to zero at two decimal places. A rule of “no more than 0.0040 apart” rejects the same pair, so the correction is delta=0.0040. The test records the contrasting outcomes instead of claiming that either choice is universally stricter.

It also verifies the API guard against passing both places and delta. That guard prevents an ambiguous assertion, but it cannot infer the business boundary for you. Choose one representation of the rule and name the boundary near the assertion. The documented delta keyword was added in Python 3.2. See the official assertAlmostEqual documentation.

AI assistance disclosure: this synthetic example was drafted with AI assistance and should be adapted to the project’s stated tolerance rule.

import unittest

case = unittest.TestCase()
expected = 10.0000
observed = 10.0049

case.assertAlmostEqual(expected, observed, places=2)
places_verdict = "accepted"

try:
    case.assertAlmostEqual(expected, observed, delta=0.0040)
except AssertionError:
    delta_verdict = "rejected"
else:
    raise AssertionError("the absolute boundary should reject this pair")

try:
    case.assertAlmostEqual(expected, observed, places=2, delta=0.0040)
except TypeError:
    mutual_exclusion = "TypeError"
else:
    raise AssertionError("places and delta must not be combined")

print(f"places={places_verdict}")
print(f"delta={delta_verdict}")
print(f"both={mutual_exclusion}")
places=accepted
delta=rejected
both=TypeError