_input_validation.py 474 B

1234567891011121314151617
  1. import math
  2. import operator
  3. def _nonneg_int_or_fail(n, var_name, strict=True):
  4. try:
  5. if strict:
  6. # Raises an exception if float
  7. n = operator.index(n)
  8. elif n == math.floor(n):
  9. n = int(n)
  10. else:
  11. raise ValueError()
  12. if n < 0:
  13. raise ValueError()
  14. except (ValueError, TypeError) as err:
  15. raise err.__class__(f"{var_name} must be a non-negative integer") from err
  16. return n