ensure_int

ensure_int(x, name: str = 'unknown', must_be: str = 'an int', *, extra='')[source][source]

Ensure a variable is an integer.

Parameters:
  • x (object) – The object to check.

  • name (str) – The name of the variable to check.

  • must_be (str) – The type of the variable to check.

  • extra (str) – Extra text to add to the error message.

Notes

This is preferred over numbers.Integral, see: https://github.com/scipy/scipy/pull/7351#issuecomment-299713159

Examples

>>> ensure_int(1)
1
>>> ensure_int(1.0)
Traceback (most recent call last):
...
TypeError: unknown must be an int, got <class 'float'>
>>> ensure_int('1')
Traceback (most recent call last):
...
TypeError: unknown must be an int, got <class 'str'>
>>> ensure_int('1.0', extra='a string')
Traceback (most recent call last):
...
TypeError: unknown must be an int a string, got <class 'str'>