3. fastnumbers API

3.1. The “Built-In Replacement” Functions

Each of these functions acts as a faster drop-in replacement for the equivalent Python built-in function.

3.1.1. float()

fastnumbers.float(x=0)

Drop-in but faster replacement for the built-in float.

Behaves identically to the built-in float except for the following:

  • Is implemented as a function, not a class, which means it cannot be sub-classed, and has no fromhex classmethod.
  • A ValueError will be raised instead of a UnicodeEncodeError if a partial surrogate is given as input.

3.1.2. int()

fastnumbers.int(x=0, base=10)

Drop-in but faster replacement for the built-in int.

Behaves identically to the built-in int except for the following:

  • Cannot convert from the __trunc__ special method of an object.
  • Is implemented as a function, not a class, which means it cannot be sub-classed, and has no from_bytes classmethod.

3.1.3. real()

fastnumbers.real(x=0.0, coerce=True)

Convert to float or int, whichever is most appropriate.

If an int literal or string containing an int is provided, then an int will be returned. If a float literal or a string containing a non-int and non-complex number is provided, a float will be returned.

If coerce is True (the default), then if a float is given that has no decimal places after conversion or only zeros after the decimal point, it will be returned as an int instead of a float.

3.2. The “Error-Handling” Functions

Each of these functions will quickly convert strings to numbers (and also numbers to numbers) with fast and convenient error handling. They are guaranteed to return results identical to the built-in float or int functions.

3.2.1. fast_real()

fastnumbers.fast_real(x, default=None, raise_on_invalid=False, key=None, nan=None, inf=None, coerce=True)

Quickly convert input to an int or float depending on value.

Any input that is valid for the built-in float or int functions will be converted to either a float or int. An input of a single numeric unicode character is also valid. The return value is guaranteed to be of type str, int, or float (or long on Python2).

If the given input is a string and cannot be converted to a float or int, it will be returned as-is unless default or raise_on_invalid is given.

Parameters:
  • input ({str, float, int, long}) – The input you wish to convert to a real number.
  • default (optional) – This value will be returned instead of the input when the input cannot be converted. Has no effect if raise_on_invalid is True.
  • raise_on_invalid (bool, optional) – If True, a ValueError will be raised if string input cannot be converted to a float or int. If False, the string will be returned as-is. The default is False.
  • key (callable, optional) – If given and the input cannot be converted, the input will be passed to the callable object and its return value will be returned. The function must take one and only one required argument.
  • nan (optional) – If the input value is NAN or can be parsed as NAN, return this value instead of NAN.
  • inf (optional) – If the input value is INF or can be parsed as INF, return this value instead of INF.
  • coerce (bool, optional) – If the input can be converted to an int without loss of precision (even if the input was a float or float-containing str) coerce to an int rather than returning a float.
Returns:

out – If the input could be converted to an int, the return type will be int (or long on Python2 if the integer is large enough). If the input could be converted to a float but not an int, the return type will be float. Otherwise, the input str will be returned as-is (if raise_on_invalid is False) or whatever value is assigned to default if default is not None.

Return type:

{str, float, int, long}

Raises:
  • TypeError – If the input is not one of str, float, or int (or long on Python2).
  • ValueError – If raise_on_invalid is True, this will be raised if the input string cannot be converted to a float or int.

See also

isreal(), real()

Examples

>>> from fastnumbers import fast_real
>>> fast_real('56')
56
>>> fast_real('56.0')
56
>>> fast_real('56.0', coerce=False)
56.0
>>> fast_real('56.07')
56.07
>>> fast_real('56.07 lb')
'56.07 lb'
>>> fast_real(56.07)
56.07
>>> fast_real(56.0)
56
>>> fast_real(56.0, coerce=False)
56.0
>>> fast_real(56)
56
>>> fast_real('invalid', default=50)
50
>>> fast_real('invalid', 50)  # 'default' is first optional positional arg
50
>>> fast_real('nan')
nan
>>> fast_real('nan', nan=0)
0
>>> fast_real('56.07', nan=0)
56.07
>>> fast_real('56.07 lb', raise_on_invalid=True) 
Traceback (most recent call last):
  ...
ValueError: could not convert string to float: '56.07 lb'
>>> fast_real('invalid', key=len)
7

Notes

It is roughly equivalent to (but much faster than)

>>> def py_fast_real(input, default=None, raise_on_invalid=False,
...                  key=None, nan=None, inf=None):
...     import math
...     try:
...         a = float(input)
...     except ValueError:
...         if raise_on_invalid:
...             raise
...         elif key is not None:
...             return key(input)
...         elif default is not None:
...             return default
...         else:
...             return input
...     else:
...         if nan is not None and math.isnan(a):
...             return nan
...         elif inf is not None and math.isinf(a):
...             return inf
...         else:
...             return int(a) if a.is_integer() else a
...

3.2.2. fast_float()

fastnumbers.fast_float(x, default=None, raise_on_invalid=False, key=None, nan=None, inf=None)

Quickly convert input to a float.

Any input that is valid for the built-in float function will be converted to a float. An input of a single numeric unicode character is also valid. The return value is guaranteed to be of type str or float.

If the given input is a string and cannot be converted to a float it will be returned as-is unless default or raise_on_invalid is given.

Parameters:
  • input ({str, float, int, long}) – The input you wish to convert to a float.
  • default (optional) – This value will be returned instead of the input when the input cannot be converted. Has no effect if raise_on_invalid is True.
  • raise_on_invalid (bool, optional) – If True, a ValueError will be raised if string input cannot be converted to a float. If False, the string will be returned as-is. The default is False.
  • key (callable, optional) – If given and the input cannot be converted, the input will be passed to the callable object and its return value will be returned. The function must take one and only one required argument.
  • nan (optional) – If the input value is NAN or can be parsed as NAN, return this value instead of NAN.
  • inf (optional) – If the input value is INF or can be parsed as INF, return this value instead of INF.
Returns:

out – If the input could be converted to a float the return type will be float. Otherwise, the input str will be returned as-is (if raise_on_invalid is False) or whatever value is assigned to default if default is not None.

Return type:

{str, float}

Raises:
  • TypeError – If the input is not one of str, float, or int (or long on Python2).
  • ValueError – If raise_on_invalid is True, this will be raised if the input string cannot be converted to a float.

See also

isfloat(), float()

Examples

>>> from fastnumbers import fast_float
>>> fast_float('56')
56.0
>>> fast_float('56.0')
56.0
>>> fast_float('56.07')
56.07
>>> fast_float('56.07 lb')
'56.07 lb'
>>> fast_float(56.07)
56.07
>>> fast_float(56)
56.0
>>> fast_float('invalid', default=50)
50
>>> fast_float('invalid', 50)  # 'default' is first optional positional arg
50
>>> fast_float('nan')
nan
>>> fast_float('nan', nan=0.0)
0.0
>>> fast_float('56.07', nan=0.0)
56.07
>>> fast_float('56.07 lb', raise_on_invalid=True) 
Traceback (most recent call last):
  ...
ValueError: could not convert string to float: '56.07 lb'
>>> fast_float('invalid', key=len)
7

Notes

It is roughly equivalent to (but much faster than)

>>> def py_fast_float(input, default=None, raise_on_invalid=False,
...                   key=None, nan=None, inf=None):
...     try:
...         x = float(input)
...     except ValueError:
...         if raise_on_invalid:
...             raise
...         elif key is not None:
...             return key(input)
...         elif default is not None:
...             return default
...         else:
...             return input
...     else:
...         if nan is not None and math.isnan(x):
...             return nan
...         elif inf is not None and math.isinf(x):
...             return inf
...         else:
...             return x
...

3.2.3. fast_int()

fastnumbers.fast_int(x, default=None, raise_on_invalid=False, key=None, base=10)

Quickly convert input to an int.

Any input that is valid for the built-in int (or long on Python2) function will be converted to a int (or long on Python2). An input of a single digit unicode character is also valid. The return value is guaranteed to be of type str or int (or long on Python2).

If the given input is a string and cannot be converted to an int it will be returned as-is unless default or raise_on_invalid is given.

Parameters:
  • input ({str, float, int, long}) – The input you wish to convert to an int.
  • default (optional) – This value will be returned instead of the input when the input cannot be converted. Has no effect if raise_on_invalid is True.
  • raise_on_invalid (bool, optional) – If True, a ValueError will be raised if string input cannot be converted to an int. If False, the string will be returned as-is. The default is False.
  • key (callable, optional) – If given and the input cannot be converted, the input will be passed to the callable object and its return value will be returned. The function must take one and only one required argument.
  • base (int, optional) – Follows the rules of Python’s built-in int(); see it’s documentation for your Python version. If given, the input must be of type str.
Returns:

out – If the input could be converted to an int, the return type will be int (or long on Python2 if the integer is large enough). Otherwise, the input str will be returned as-is (if raise_on_invalid is False) or whatever value is assigned to default if default is not None.

Return type:

{str, int, long}

Raises:
  • TypeError – If the input is not one of str, float, or int (or long on Python2).
  • ValueError – If raise_on_invalid is True, this will be raised if the input string cannot be converted to an int.

Examples

>>> from fastnumbers import fast_int
>>> fast_int('56')
56
>>> fast_int('56.0')
'56.0'
>>> fast_int('56.07 lb')
'56.07 lb'
>>> fast_int(56.07)
56
>>> fast_int(56)
56
>>> fast_int('invalid', default=50)
50
>>> fast_int('invalid', 50)  # 'default' is first optional positional arg
50
>>> fast_int('56.07 lb', raise_on_invalid=True) 
Traceback (most recent call last):
  ...
ValueError: could not convert string to int: '56.07 lb'
>>> fast_int('invalid', key=len)
7

Notes

It is roughly equivalent to (but much faster than)

>>> def py_fast_int(input, default=None, raise_on_invalid=False, key=None):
...     try:
...         return int(input)
...     except ValueError:
...         if raise_on_invalid:
...             raise
...         elif key is not None:
...             return key(input)
...         elif default is not None:
...             return default
...         else:
...             return input
...

3.2.4. fast_forceint()

fastnumbers.fast_forceint(x, default=None, raise_on_invalid=False, key=None)

Quickly convert input to an int, truncating if is a float.

Any input that is valid for the built-in int (or long on Python2) function will be converted to a int (or long on Python2). An input of a single numeric unicode character is also valid. The return value is guaranteed to be of type str or int (or long on Python2).

In addition to the above, any input valid for the built-in float will be parsed and the truncated to the nearest integer; for example, ‘56.07’ will be converted to 56.

If the given input is a string and cannot be converted to an int it will be returned as-is unless default or raise_on_invalid is given.

Parameters:
  • input ({str, float, int, long}) – The input you wish to convert to an int.
  • default (optional) – This value will be returned instead of the input when the input cannot be converted. Has no effect if raise_on_invalid is True
  • raise_on_invalid (bool, optional) – If True, a ValueError will be raised if string input cannot be converted to an int. If False, the string will be returned as-is. The default is False.
  • key (callable, optional) – If given and the input cannot be converted, the input will be passed to the callable object and its return value will be returned. The function must take one and only one required argument.
Returns:

out – If the input could be converted to an int, the return type will be int (or long on Python2 if the integer is large enough). Otherwise, the input str will be returned as-is (if raise_on_invalid is False) or whatever value is assigned to default if default is not None.

Return type:

{str, int, long}

Raises:
  • TypeError – If the input is not one of str, float, or int (or long on Python2).
  • ValueError – If raise_on_invalid is True, this will be raised if the input string cannot be converted to an int.

Examples

>>> from fastnumbers import fast_forceint
>>> fast_forceint('56')
56
>>> fast_forceint('56.0')
56
>>> fast_forceint('56.07')
56
>>> fast_forceint('56.07 lb')
'56.07 lb'
>>> fast_forceint(56.07)
56
>>> fast_forceint(56)
56
>>> fast_forceint('invalid', default=50)
50
>>> fast_forceint('invalid', 50)  # 'default' is first optional positional arg
50
>>> fast_forceint('56.07 lb', raise_on_invalid=True) 
Traceback (most recent call last):
  ...
ValueError: could not convert string to float: '56.07 lb'
>>> fast_forceint('invalid', key=len)
7

Notes

It is roughly equivalent to (but much faster than)

>>> def py_fast_forceint(input, default=None, raise_on_invalid=False, key=None):
...     try:
...         return int(input)
...     except ValueError:
...         try:
...             return int(float(input))
...         except ValueError:
...             if raise_on_invalid:
...                 raise
...             elif key is not None:
...                 return key(input)
...             elif default is not None:
...                 return default
...             else:
...                 return input
...

3.3. The “Checking” Functions

These functions return a Boolean value that indicates if the input can return a certain number type or not.

3.3.1. isreal()

fastnumbers.isreal(x, str_only=False, num_only=False, allow_inf=False, allow_nan=False)

Quickly determine if a string is a real number.

Returns True if the input is valid input for the built-in float or int functions, or is a single valid numeric unicode character.

The input may be whitespace-padded.

Parameters:
  • input – The input you wish to test if it is a real number.
  • str_only (bool, optional) – If True, then any non-str input will cause this function to return False. The default is False.
  • num_only (bool, optional) – If True, then any str input will cause this function to return False. The default is False.
  • allow_inf (bool, optional) – If True, then the strings ‘inf’ and ‘infinity’ will also return True. This check is case-insensitive, and the string may be signed (i.e. ‘+/-‘). The default is False.
  • allow_nan (bool, optional) – If True, then the string ‘nan’ will also return True. This check is case-insensitive, and the string may be signed (i.e. ‘+/-‘). The default is False.
Returns:

result – Whether or not the input is a real number.

Return type:

bool

See also

fast_real()

Examples

>>> from fastnumbers import isreal
>>> isreal('56')
True
>>> isreal('56.07')
True
>>> isreal('56.07', num_only=True)
False
>>> isreal('56.07 lb')
False
>>> isreal(56.07)
True
>>> isreal(56.07, str_only=True)
False
>>> isreal(56)
True
>>> isreal('nan')
False
>>> isreal('nan', allow_nan=True)
True

Notes

It is roughly equivalent to (but much faster than)

>>> import re
>>> def py_isreal(input, str_only=False, num_only=False,
...               allow_nan=False, allow_inf=False):
...     if str_only and type(input) != str:
...         return False
...     if num_only and type(input) not in (float, int):
...         return False
...     try:
...         x = bool(re.match(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$', input))
...     except TypeError:
...         return type(input) in (float, int)
...     else:
...         if x:
...             return True
...         elif allow_inf and input.lower().strip().lstrip('-+') in ('inf', 'infinity'):
...             return True
...         elif allow_nan and input.lower().strip().lstrip('-+') == 'nan':
...             return True
...         else:
...             return False
...

3.3.2. isfloat()

fastnumbers.isfloat(x, str_only=False, num_only=False, allow_inf=False, allow_nan=False)

Quickly determine if a string is a float.

Returns True if the input is valid input for the built-in float function, is already a valid float, or is a single valid numeric unicode character. It differs from isreal in that an int input will return False.

The input may be whitespace-padded.

Parameters:
  • input – The input you wish to test if it is a float.
  • str_only (bool, optional) – If True, then any non-str input will cause this function to return False. The default is False.
  • num_only (bool, optional) – If True, then any str input will cause this function to return False. The default is False.
  • allow_inf (bool, optional) – If True, then the strings ‘inf’ and ‘infinity’ will also return True. This check is case-insensitive, and the string may be signed (i.e. ‘+/-‘). The default is False.
  • allow_nan (bool, optional) – If True, then the string ‘nan’ will also return True. This check is case-insensitive, and the string may be signed (i.e. ‘+/-‘). The default is False.
Returns:

result – Whether or not the input is a float.

Return type:

bool

Examples

>>> from fastnumbers import isfloat
>>> isfloat('56')
True
>>> isfloat('56.07')
True
>>> isreal('56.07', num_only=True)
False
>>> isfloat('56.07 lb')
False
>>> isfloat(56.07)
True
>>> isfloat(56.07, str_only=True)
False
>>> isfloat(56)
False
>>> isfloat('nan')
False
>>> isfloat('nan', allow_nan=True)
True

Notes

It is roughly equivalent to (but much faster than)

>>> import re
>>> def py_isfloat(input, str_only=False, num_only=False,
...                allow_nan=False, allow_inf=False):
...     if str_only and type(input) != str:
...         return False
...     if num_only and type(input) != float:
...         return False
...     try:
...         x = bool(re.match(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$', input))
...     except TypeError:
...         return type(input) == float
...     else:
...         if x:
...             return True
...         elif allow_inf and input.lower().strip().lstrip('-+') in ('inf', 'infinity'):
...             return True
...         elif allow_nan and input.lower().strip().lstrip('-+') == 'nan':
...             return True
...         else:
...             return False

3.3.3. isint()

fastnumbers.isint(x, str_only=False, num_only=False)

Quickly determine if a string is an int.

Returns True if the input is valid input for the built-in int function, is already a valid int, or is a single valid digit unicode character. It differs from isintlike in that a float input will return False and that int-like strings (i.e. ‘45.0’) will return False.

The input may be whitespace-padded.

Parameters:
  • input – The input you wish to test if it is an int.
  • str_only (bool, optional) – If True, then any non-str input will cause this function to return False. The default is False.
  • num_only (bool, optional) – If True, then any str input will cause this function to return False. The default is False.
Returns:

result – Whether or not the input is an int.

Return type:

bool

Examples

>>> from fastnumbers import isint
>>> isint('56')
True
>>> isint('56', num_only=True)
False
>>> isint('56.07')
False
>>> isint('56.07 lb')
False
>>> isint(56.07)
False
>>> isint(56)
True
>>> isint(56, str_only=True)
False

Notes

It is roughly equivalent to (but much faster than)

>>> import re
>>> def py_isint(input, str_only=False, num_only=False):
...     if str_only and type(input) != str:
...         return False
...     if num_only and type(input) != int:
...         return False
...     try:
...         return bool(re.match(r'[-+]?\d+$', input))
...     except TypeError:
...         return False
...

3.3.4. isintlike()

fastnumbers.isintlike(x, str_only=False, num_only=False)

Quickly determine if a string (or object) is an int or int-like.

Returns True if the input is valid input for the built-in int function, is already a valid int or float, or is a single valid numeric unicode character. It differs from isintlike in that int-like floats or strings (i.e. ‘45.0’) will return True.

The input may be whitespace-padded.

Parameters:input – The input you wish to test if it is a int-like.
Returns:
  • result (bool) – Whether or not the input is an int.
  • str_only (bool, optional) – If True, then any non-str input will cause this function to return False. The default is False.
  • num_only (bool, optional) – If True, then any str input will cause this function to return False. The default is False.

See also

fast_forceint()

Examples

>>> from fastnumbers import isintlike
>>> isintlike('56')
True
>>> isintlike('56', num_only=True)
False
>>> isintlike('56.07')
False
>>> isintlike('56.0')
True
>>> isintlike('56.07 lb')
False
>>> isintlike(56.07)
False
>>> isintlike(56.0)
True
>>> isintlike(56.0, str_only=True)
False
>>> isintlike(56)
True

Notes

It is roughly equivalent to (but much faster than)

>>> import re
>>> def py_isintlike(input, str_only=False, num_only=False):
...     if str_only and type(input) != str:
...         return False
...     if num_only and type(input) not in (int, float):
...         return False
...     try:
...         if re.match(r'[-+]?\d+$', input):
...             return True
...         elif re.match(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$', input):
...             return float(input).is_integer()
...         else:
...             return False
...     except TypeError:
...         if type(input) == float:
...             return input.is_integer()
...         elif type(input) == int:
...             return True
...         else:
...             return False
...