almost¶
-
privex.helpers.common.
almost
(compare: Union[decimal.Decimal, int, float, str], *numbers: Union[decimal.Decimal, int, float, str], tolerance: Union[decimal.Decimal, int, float, str] = Decimal('0.01'), **kwargs) → bool[source]¶ Compare two or more numbers, returning
True
if allnumbers
are no more thantolerance
greater or smaller than thancompare
- otherwiseFalse
.Works similarly to
unittest.TestCase.assertAlmostEqual()
Basic usage with two numbers + default tolerance (
0.01
):>>> almost('5', '5.001') True >>> almost('5', '5.5') False
Multiple numbers + custom tolerance:
>>> almost('5', '5.14', '4.85', '5.08', tolerance=Decimal('0.2')) True >>> almost('5', '5.3', '4.85', '5.08', tolerance=Decimal('0.2')) False
Using
fail
ortest
:>>> # By passing ``fail=True``, a descriptive AssertionError is raised when the tolerance check fails. >>> almost('5', '5.01', fail=True) True >>> almost('5', '5.02', fail=True) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "privex/helpers/common.py", line 1044, in almost raise AssertionError( AssertionError: Number at position 0 (val: 5.02) failed tolerance (0.01) check against 5 >>> # By passing ``test=True``, a standard ``assert`` will be used to compare the numbers. >>> almost('5', '5.01', test=True) True >>> almost('5', '5.02', test=True) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "privex/helpers/common.py", line 1041, in almost assert (x - tolerance) <= compare <= (x + tolerance) AssertionError
- Parameters
compare (Decimal|int|float|str) – The base number which all
numbers
will be compared against.numbers (Decimal|int|float|str) – One or more numbers to compare against
compare
tolerance (Decimal|int|float|str) – (kwarg only) Amount that each
numbers
can be greater/smaller thancompare
before returningFalse
.fail (bool) – (default:
False
) If true, will raiseAssertionError
on failed tolerance check, instead of returningFalse
. (mutually exclusive withassert
)test (bool) – (default:
False
) If true, will useassert
instead of testing withif
. Useful in unit tests. (mutually exclusive withraise
)
- Raises
AttributeError – When less than 1 number is present in
numbers
AssertionError – When kwarg
raise
isTrue
and one or more numbers failed the tolerance check.
- Return bool is_almost
True
if allnumbers
are withintolerance
ofcompare
,False
if one or morenumbers
is outside of the tolerance.