Pytest: assert almost equal
One of the easiest ways to assert near-equality of floats in pytest is with pytest.approx()
.
Example:
You can also customize the tolerance level with abs
or rel
parameters.
Tolerance Example:
In the remainder of the post, we'll dive deeper and explore more complex cases, as well as other tools at your disposal.
Cold-hard syntax and pytest for tough problems
Sometimes, problems might get a bit more complex than what you'd expect.
Comparing Bloated Tuples
If you have tuples or lists of floats, instead of going through each element in a painstaking manner, use this neat trick involving map
and all
functions.
The above code essentially loops through the tuples and checks the difference of each pair, making your tests clear and snappy.
Alternatives with NumPy and Unittest
If you're more inclined to the NumPy or unittest libraries, they provide excellent ways to assert near equality of floats.
NumPy's assert_allclose
:
Unittest's assertAlmostEqual
:
Adding Flexibility with Custom Functions
Creating your own custom function can provide the ultimate flexibility and help you adapt to any specific use case.
Clear, Precision Strikes with math.isclose()
You don't have to sacrifice precision for clear code. Python's math.isclose()
is a prime example of such balance:
With good use of comments, you can explain tricky parts of your code, or hide dad jokes in plain sight.
Learning from Errors
Wisely utilizing error messages from assertions can make debugging an enjoyable part of your process:
These messages provide crucial information about assertion failures and help speed up debugging.
Was this article helpful?