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 all numbers are no more than tolerance greater or smaller than than compare - otherwise False.

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 or test:

>>> # 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 than compare before returning False.

  • fail (bool) – (default: False) If true, will raise AssertionError on failed tolerance check, instead of returning False. (mutually exclusive with assert)

  • test (bool) – (default: False) If true, will use assert instead of testing with if. Useful in unit tests. (mutually exclusive with raise)

Raises
  • AttributeError – When less than 1 number is present in numbers

  • AssertionError – When kwarg raise is True and one or more numbers failed the tolerance check.

Return bool is_almost

True if all numbers are within tolerance of compare, False if one or more numbers is outside of the tolerance.