2. fastnumbers API

2.1. The “Built-In Replacement” Functions

Each of these functions acts as a (potentially) faster drop-in replacement for the equivalent Python built-in function. Please perform timing tests on your platform with your data to determine if these functions will actually provide you with a speed-up.

2.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.

  • You cannot use this function in isinstance.

If you need any of the above functionality you can still access the original float class through builtins.

>>> from fastnumbers import float
>>> isinstance(9.4, float)  
Traceback (most recent call last):
    ...
TypeError: ...
>>> import builtins
>>> isinstance(9.4, builtins.float)
True

2.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.

  • You cannot use this function in isinstance.

If you need any of the above functionality you can still access the original int class through builtins.

>>> from fastnumbers import int
>>> isinstance(9, int) 
Traceback (most recent call last):
    ...
TypeError: ...
>>> import builtins
>>> isinstance(9, builtins.int)
True

2.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.

2.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.

2.2.1. try_real()

fastnumbers.try_real(x, *, inf=fastnumbers.ALLOWED, nan=fastnumbers.ALLOWED, on_fail=fastnumbers.INPUT, on_type_error=fastnumbers.RAISE, coerce=True, allow_underscores=False, map=False)

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.

If the given input is a string and cannot be converted to a float or int it will be returned as-is unless on_fail indicates otherwise.

Parameters
  • input ({str, float, int} or iterable of {str, float, int}) – The input you wish to convert to a real number - must be an iterable of inputs if map is not False.

  • inf (optional) – Control how INF is interpreted/handled. The default is ALLOWED, which indicates that both the string “inf” or the float INF are accepted. Other valid values are INPUT to indicate that if given this value it should be returned as-is, RAISE to indicate a ValueError should be raised, a callable accepting a single argument that will be called with the input to return an alternate value, or a default value to be returned instead of INF.

  • nan (optional) – Control how NaN is interpreted/handled. Behavior matches that of inf except it is for the string “nan” and the value NaN.

  • on_fail (optional) – Control what happens when an input string cannot be converted. The default is INPUT which indicates that the value should be returned as-is. Other valid values are RAISE to indicate a ValueError should be raised, a callable accepting a single argument that will be called with the input to return an alternate value, or a default value to be returned instead of the input.

  • on_type_error (optional) – Control what happens when the input is neither numeric nor string. Behavior matches that of on_fail except that the default value is RAISE and a TypeError is raised instead of ValueError.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.

  • denoise (bool, optional) – When coercing large floating point numbers to an integer, ensure that “noise” digits are not included. See README for more details. Ignored if coerce is False. The default is False.

  • allow_underscores (bool, optional) – Underscores are allowed in numeric literals and in strings passed to int or float (see PEP 515 for details on what is and is not allowed). You can enable that behavior by setting this option to True - the default is False.

  • map (bool or type(list), optional) – If True or list, instead of accepting a single value to convert this function accepts an iterable of values to convert. If True it returns an iterable of the results, and if list it returns a list of the results. The default is False.

Returns

out – If the input could be converted to an int, the return type will be int. If the input could be converted to a float but not an int, the return type will be float. Otherwise, the return value can be manipulated. by the value of on_fail, on_type_error, inf, or nan. If map is True, then the output will be an iterator of these things. If map is list, then the output will be a list of these things.

Return type

{str, float, int} or list of {str, float, int}

Raises
  • TypeError – If the input is not one of str, float, or int and on_type_error is set to RAISE.

  • ValueError – If one of on_fail, inf, or nan are set to RAISE and a triggering event is set.

See also

check_real, real

Examples

>>> from fastnumbers import RAISE, try_real
>>> try_real('56')
56
>>> try_real('56.0')
56
>>> try_real('56.0', coerce=False)
56.0
>>> try_real('56.07')
56.07
>>> try_real('56.07 lb')
'56.07 lb'
>>> try_real(56.07)
56.07
>>> try_real(56.0)
56
>>> try_real(56.0, coerce=False)
56.0
>>> try_real(56)
56
>>> try_real('invalid', on_fail=50)
50
>>> try_real('nan')
nan
>>> try_real('nan', nan=0)
0
>>> try_real('56.07', nan=0)
56.07
>>> try_real('56.07 lb', on_fail=RAISE) 
Traceback (most recent call last):
  ...
ValueError: could not convert string to float: '56.07 lb'
>>> try_real('invalid', on_fail=len)
7
>>> try_real(['56.0', '56.07'], map=list)
[56, 56.07]

2.2.2. try_float()

fastnumbers.try_float(x, *, inf=fastnumbers.ALLOWED, nan=fastnumbers.ALLOWED, on_fail=fastnumbers.INPUT, on_type_error=fastnumbers.RAISE, allow_underscores=False, map=False)

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.

If the given input is a string and cannot be converted to a float it will be returned as-is unless on_fail indicates otherwise.

Parameters
  • input ({str, float, int} or iterable of {str, float, int}) – The input you wish to convert to a float - must be an iterable of inputs if map is not False.

  • inf (optional) – Control how INF is interpreted/handled. The default is ALLOWED, which indicates that both the string “inf” or the float INF are accepted. Other valid values are INPUT to indicate that if given this value it should be returned as-is, RAISE to indicate a ValueError should be raised, a callable accepting a single argument that will be called with the input to return an alternate value, or a default value to be returned instead of INF.

  • nan (optional) – Control how NaN is interpreted/handled. Behavior matches that of inf except it is for the string “nan” and the value NaN.

  • on_fail (optional) – Control what happens when an input string cannot be converted to a float. The default is INPUT which indicates that the value should be returned as-is. Other valid values are RAISE to indicate a ValueError should be raised, a callable accepting a single argument that will be called with the input to return an alternate value, or a default value to be returned instead of the input.

  • on_type_error (optional) – Control what happens when the input is neither numeric nor string. Behavior matches that of on_fail except that the default value is RAISE and a TypeError is raised instead of ValueError.allow_underscores : bool, optional Underscores are allowed in numeric literals and in strings passed to int or float (see PEP 515 for details on what is and is not allowed). You can enable that behavior by setting this option to True - the default is False.

  • map (bool or type(list), optional) – If True or list, instead of accepting a single value to convert this function accepts an iterable of values to convert. If True it returns an iterable of the results, and if list it returns a list of the results. The default is False.

Returns

out – If the input could be converted to a float the return type will be float. Otherwise, the return value can be manipulated. by the value of on_fail, on_type_error, inf, or nan. If map is True, then the output will be an iterator of these things. If map is list, then the output will be a list of these things.

Return type

{str, float} or list of {str, float}

Raises
  • TypeError – If the input is not one of str, float, or int and on_type_error is set to RAISE.

  • ValueError – If one of on_fail, inf, or nan are set to RAISE and a triggering event is set.

See also

check_float, float

Examples

>>> from fastnumbers import RAISE, try_float
>>> try_float('56')
56.0
>>> try_float('56.0')
56.0
>>> try_float('56.07')
56.07
>>> try_float('56.07 lb')
'56.07 lb'
>>> try_float(56.07)
56.07
>>> try_float(56)
56.0
>>> try_float('invalid', on_fail=50)
50
>>> try_float('nan')
nan
>>> try_float('nan', nan=0.0)
0.0
>>> try_float('56.07', nan=0.0)
56.07
>>> try_float('56.07 lb', on_fail=RAISE) 
Traceback (most recent call last):
  ...
ValueError: could not convert string to float: '56.07 lb'
>>> try_float('invalid', on_fail=len)
7
>>> try_float(['56.0', '56.07'], map=list)
[56.0, 56.07]

2.2.3. try_int()

fastnumbers.try_int(x, *, on_fail=fastnumbers.INPUT, on_type_error=fastnumbers.RAISE, base=10, allow_underscores=False, map=False)

Quickly convert input to an int.

Any input that is valid for the built-in int function will be converted to a int. An input of a single digit unicode character is also valid.

If the given input is a string and cannot be converted to an int it will be returned as-is unless on_fail indicates otherwise.

Parameters
  • input ({str, float, int} or iterable of {str, float, int}) – The input you wish to convert to an int - must be an iterable of inputs if map is not False.

  • on_fail (optional) – Control what happens when an input string cannot be converted to an int. The default is INPUT which indicates that the value should be returned as-is. Other valid values are RAISE to indicate a ValueError should be raised, a callable accepting a single argument that will be called with the input to return an alternate value, or a default value to be returned instead of the input.

  • on_type_error (optional) – Control what happens when the input is neither numeric nor string. Behavior matches that of on_fail except that the default value is RAISE and a TypeError is raised instead of ValueError.base : int, optional Follows the rules of Python’s built-in :func:int; see it’s documentation for your Python version. If given, the input must be of type str.

  • allow_underscores (bool, optional) – Underscores are allowed in numeric literals and in strings passed to int or float (see PEP 515 for details on what is and is not allowed). You can enable that behavior by setting this option to True - the default is False.

  • map (bool or type(list), optional) – If True or list, instead of accepting a single value to convert this function accepts an iterable of values to convert. If True it returns an iterable of the results, and if list it returns a list of the results. The default is False.

Returns

out – If the input could be converted to an int, the return type will be int. Otherwise, the return value can be manipulated. by the value of on_fail or on_type_error. If map is True, then the output will be an iterator of these things. If map is list, then the output will be a list of these things.

Return type

{str, int} or list of {str, int}

Raises
  • TypeError – If the input is not one of str, float, or int and on_type_error is set to RAISE.

  • ValueError – If one of on_fail, inf, or nan are set to RAISE and a triggering event is set.

Examples

>>> from fastnumbers import RAISE, try_int
>>> try_int('56')
56
>>> try_int('56.0')
'56.0'
>>> try_int('56.07 lb')
'56.07 lb'
>>> try_int(56.07)
56
>>> try_int(56)
56
>>> try_int('13af')
'13af'
>>> try_int('13af', base=16)
5039
>>> try_int('0x13af')
'0x13af'
>>> try_int('0x13af', base=0)  # detect base from prefix
5039
>>> try_int('invalid', on_fail=50)
50
>>> try_int('56.07 lb', on_fail=RAISE) 
Traceback (most recent call last):
  ...
ValueError: could not convert string to int: '56.07 lb'
>>> try_int('invalid', on_fail=len)
7
>>> try_int(['56', '56.07'], map=list)
[56, 56.07]

2.2.4. try_forceint()

fastnumbers.try_forceint(x, *, on_fail=fastnumbers.INPUT, on_type_error=fastnumbers.RAISE, allow_underscores=False, map=False)

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

Any input that is valid for the built-in int function will be converted to a int. An input of a single numeric unicode character is also valid.

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 on_fail indicates otherwise.

Parameters
  • input ({str, float, int} or iterable of {str, float, int}) – The input you wish to convert to an int - must be an iterable of inputs if map is not False.

  • on_fail (optional) – Control what happens when an input string cannot be converted to an int. The default is INPUT which indicates that the value should be returned as-is. Other valid values are RAISE to indicate a ValueError should be raised, a callable accepting a single argument that will be called with the input to return an alternate value, or a default value to be returned instead of the input.

  • on_type_error (optional) – Control what happens when the input is neither numeric nor string. Behavior matches that of on_fail except that the default value is RAISE and a TypeError is raised instead of ValueError.denoise : bool, optional When converting large floating point numbers to an integer, ensure that “noise” digits are not included. See README for more details. The default is False.

  • allow_underscores (bool, optional) – Underscores are allowed in numeric literals and in strings passed to int or float (see PEP 515 for details on what is and is not allowed). You can enable that behavior by setting this option to True - the default is False.

  • map (bool or type(list), optional) – If True or list, instead of accepting a single value to convert this function accepts an iterable of values to convert. If True it returns an iterable of the results, and if list it returns a list of the results. The default is False.

Returns

out – If the input could be converted to an int, the return type will be int. Otherwise, the return value can be manipulated. by the value of on_fail or on_type_error. If map is True, then the output will be an iterator of these things. If map is list, then the output will be a list of these things.

Return type

{str, int} or list of {str, int}

Raises
  • TypeError – If the input is not one of str, float, or int and on_type_error is set to RAISE.

  • ValueError – If one of on_fail, inf, or nan are set to RAISE and a triggering event is set.

Examples

>>> from fastnumbers import RAISE, try_forceint
>>> try_forceint('56')
56
>>> try_forceint('56.0')
56
>>> try_forceint('56.07')
56
>>> try_forceint('56.07 lb')
'56.07 lb'
>>> try_forceint(56.07)
56
>>> try_forceint(56)
56
>>> try_forceint('invalid', on_fail=50)
50
>>> try_forceint('56.07 lb', on_fail=RAISE) 
Traceback (most recent call last):
  ...
ValueError: could not convert string to float: '56.07 lb'
>>> try_forceint('invalid', on_fail=len)
7
>>> try_forceint(['56', '56.07'], map=list)
[56, 56]

2.2.5. try_array()

fastnumbers.try_array(input: Iterable[Any], output: None = None, *, dtype: IntT, inf: ALLOWED_T | int | CallToInt = ALLOWED, nan: ALLOWED_T | int | CallToInt = ALLOWED, on_fail: RAISE_T | int | CallToInt = RAISE, on_overflow: RAISE_T | int | CallToInt = RAISE, on_type_error: RAISE_T | int | CallToInt = RAISE, base: int = 10, allow_underscores: bool = False) np.ndarray[IntT]
fastnumbers.try_array(input: Iterable[Any], output: None = None, *, dtype: FloatT = np.float64, inf: ALLOWED_T | int | float | CallToInt | CallToFloat = ALLOWED, nan: ALLOWED_T | int | float | CallToInt | CallToFloat = ALLOWED, on_fail: RAISE_T | int | float | CallToInt | CallToFloat = RAISE, on_overflow: RAISE_T | int | float | CallToInt | CallToFloat = RAISE, on_type_error: RAISE_T | int | float | CallToInt | CallToFloat = RAISE, base: int = 10, allow_underscores: bool = False) np.ndarray[FloatT]
fastnumbers.try_array(input: Iterable[Any], output: np.ndarray[IntT], *, inf: ALLOWED_T | int | CallToInt = ALLOWED, nan: ALLOWED_T | int | CallToInt = ALLOWED, on_fail: RAISE_T | int | CallToInt = RAISE, on_overflow: RAISE_T | int | CallToInt = RAISE, on_type_error: RAISE_T | int | CallToInt = RAISE, base: int = 10, allow_underscores: bool = False) None
fastnumbers.try_array(input: Iterable[Any], output: np.ndarray[FloatT], *, inf: ALLOWED_T | int | float | CallToInt | CallToFloat = ALLOWED, nan: ALLOWED_T | int | float | CallToInt | CallToFloat = ALLOWED, on_fail: RAISE_T | int | float | CallToInt | CallToFloat = RAISE, on_overflow: RAISE_T | int | float | CallToInt | CallToFloat = RAISE, on_type_error: RAISE_T | int | float | CallToInt | CallToFloat = RAISE, base: int = 10, allow_underscores: bool = False) None
fastnumbers.try_array(input: Iterable[Any], output: array.array[int], *, inf: ALLOWED_T | int | CallToInt = ALLOWED, nan: ALLOWED_T | int | CallToInt = ALLOWED, on_fail: RAISE_T | int | CallToInt = RAISE, on_overflow: RAISE_T | int | CallToInt = RAISE, on_type_error: RAISE_T | int | CallToInt = RAISE, base: int = 10, allow_underscores: bool = False) None
fastnumbers.try_array(input: Iterable[Any], output: array.array[float], *, inf: ALLOWED_T | int | float | CallToInt | CallToFloat = ALLOWED, nan: ALLOWED_T | int | float | CallToInt | CallToFloat = ALLOWED, on_fail: RAISE_T | int | float | CallToInt | CallToFloat = RAISE, on_overflow: RAISE_T | int | float | CallToInt | CallToFloat = RAISE, on_type_error: RAISE_T | int | float | CallToInt | CallToFloat = RAISE, base: int = 10, allow_underscores: bool = False) None

Quickly convert an iterable’s contents into an array.

Is basically a direct analogue to using the map option in try_float() and friends, except that it returns an array object instead of a list, and there are more restrictions of what can be returned (since the outputs must fit inside C data-types).

Parameters
  • input – The iterable of values to convert into an array.

  • output (optional) – If specified, it is an already existing array object that will contain the converted data. It must be of the same length as the input, and must be one-dimensional (though a 1D slice of a multi-dimensional array is allowed). numpy.ndarray and array.array types are allowed. If None, a numpy.ndarray will be created for you and will be returned as the return value.

  • dtype (optional) – If output is None, this specifies the dtype of the returned ndarray. The default is np.float64. The dtype must be of integral or float type. Ignored if output is not None.

  • inf (optional) – Control how INF is interpreted/handled. The default is ALLOWED, which indicates that both the string “inf” or the float INF are accepted. Other valid values are a callable accepting a single argument that will be called with the input to return an alternate value, or a default value to be returned instead of INF. Ignored if the dtype is integral.

  • nan (optional) – Control how NaN is interpreted/handled. Behavior matches that of inf except it is for the string “nan” and the value NaN. Ignored if the dtype is integral.

  • on_fail (optional) – Control what happens when an input string cannot be converted to a float. The default is RAISE to indicate a ValueError should be raised, a callable accepting a single argument that will be called with the input to return an alternate value, or a default value to be returned instead of the input.

  • on_overflow (optional) – Control what happens when the input does not fit in the desired output data type. Behavior matches that of on_fail except that a OverflowError is raised instead of ValueError.

  • on_type_error (optional) – Control what happens when the input is neither numeric nor string. Behavior matches that of on_fail except that a TypeError is raised instead of ValueError.

  • base (int, optional) – Follows the rules of Python’s built-in :func:int; see it’s documentation for your Python version. If given, the input must be of type str. Ignored if the dtype is not integral.

  • allow_underscores (bool, optional) – Underscores are allowed in numeric literals and in strings passed to int or float (see PEP 515 for details on what is and is not allowed). You can enable that behavior by setting this option to True - the default is False.

Returns

  • ndarray – If output was None, this function will return the result in a numpy ndarray of the specified dtype.

  • None – If output was not None

Raises
  • TypeError – If the input is not one of str, float, or int and on_type_error is set to RAISE.

  • OverflowError – If the input cannot fit into the desired dtype and the dtype is of integral type and on_overflow is set to RAISE.

  • ValueError – If on_fail is set to RAISE and a triggering event is set.

  • TypeError – If output is given and it is of an invalid type (including data type).

  • RuntimeError – If output is not None but numpy is not installed.

  • TypeError – If the value (or return value of the callable) given to inf, nan, on_fail, on_overflow, or on_type_error is not a float or int.

  • OverflowError – If the dtype is integral and the value (or return value of the callable) given to on_fail, on_overflow, or on_type_error cannot fit into the data type specified.

  • ValueError – If the dtype is integral and the value (or return value of the callable) given to on_fail, on_overflow, or on_type_error is a float.

Examples

>>> from fastnumbers import try_array
>>> import numpy as np
>>> try_array(["5", "3", "8"])
array([5., 3., 8.])
>>> output = np.empty(3, dtype=np.int32)
>>> try_array(["5", "3", "8"], output=output)
>>> np.array_equal(output, np.array([5, 3, 8], dtype=np.int32))
True

2.3. The “Checking” Functions

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

2.3.1. check_real()

fastnumbers.check_real(x, *, consider=None, inf=fastnumbers.NUMBER_ONLY, nan=fastnumbers.NUMBER_ONLY, allow_underscores=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.

  • consider (optional) – Control the data types that may be interpreted. By default both string and numeric input may be considered. If given STRING_ONLY, then only string input may return True. if given NUMBER_ONLY, then only numeric input may return True. Giving None is equivalent to omitting this argument.

  • inf (optional) – Control if and in what form INF is interpreted. The default is NUMBER_ONLY, which indicates that only INF will return True. Other allowed values are STRING_ONLY, which indicates that only “inf” will return True, ALLOWED, which indicates that both “inf” and INF will return True, or DISALLOWED, which means neither will return True.

  • nan (optional) – Control if and in what form NaN is interpreted. Behavior matches that of inf except it is for the string “nan” and the value NaN.

  • allow_underscores (bool, optional) – Underscores are allowed in numeric literals and in strings passed to int or float (see PEP 515 for details on what is and is not allowed). You can enable that behavior by setting this option to True - the default is False.

Returns

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

Return type

bool

See also

try_real

Examples

>>> from fastnumbers import ALLOWED, DISALLOWED, NUMBER_ONLY, STRING_ONLY, check_real
>>> check_real('56')
True
>>> check_real('56.07')
True
>>> check_real('56.07', consider=NUMBER_ONLY)
False
>>> check_real('56.07 lb')
False
>>> check_real(56.07)
True
>>> check_real(56.07, consider=STRING_ONLY)
False
>>> check_real(56)
True
>>> check_real('nan')
False
>>> check_real('nan', nan=ALLOWED)
True
>>> check_real(float('nan'))
True
>>> check_real(float('nan'), nan=DISALLOWED)
False

2.3.2. check_float()

fastnumbers.check_float(x, *, consider=None, inf=fastnumbers.NUMBER_ONLY, nan=fastnumbers.NUMBER_ONLY, strict=False, allow_underscores=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 check_real 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.

  • consider (optional) – Control the data types that may be interpreted. By default both string and numeric input may be considered. If given STRING_ONLY, then only string input may return True. if given NUMBER_ONLY, then only numeric input may return True. Giving None is equivalent to omitting this argument.

  • inf (optional) – Control if and in what form INF is interpreted. The default is NUMBER_ONLY, which indicates that only INF will return True. Other allowed values are STRING_ONLY, which indicates that only “inf” will return True, ALLOWED, which indicates that both “inf” and INF will return True, or DISALLOWED, which means neither will return True.

  • nan (optional) – Control if and in what form NaN is interpreted. Behavior matches that of inf except it is for the string “nan” and the value NaN.

  • strict (bool, optional) – Control whether a string must be strictly represented as a float. If True, then the string “56.0” would return True but “56” would return False. If False (the default), then both of the strings “56.0” and “56” would return True.

  • allow_underscores (bool, optional) – Underscores are allowed in numeric literals and in strings passed to int or float (see PEP 515 for details on what is and is not allowed). You can enable that behavior by setting this option to True - the default is False.

Returns

result – Whether or not the input is a float.

Return type

bool

See also

try_float, check_real

Examples

>>> from fastnumbers import ALLOWED, DISALLOWED, NUMBER_ONLY, STRING_ONLY, check_float
>>> check_float('56')
True
>>> check_float('56', strict=True)
False
>>> check_float('56.07')
True
>>> check_float('56.07', consider=NUMBER_ONLY)
False
>>> check_float('56.07 lb')
False
>>> check_float(56.07)
True
>>> check_float(56.07, consider=STRING_ONLY)
False
>>> check_float(56)
False
>>> check_float('nan')
False
>>> check_float('nan', nan=ALLOWED)
True
>>> check_float(float('nan'))
True
>>> check_float(float('nan'), nan=DISALLOWED)
False

2.3.3. check_int()

fastnumbers.check_int(x, *, consider=None, base=10, allow_underscores=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 check_intlike 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.

  • consider (optional) – Control the data types that may be interpreted. By default both string and numeric input may be considered. If given STRING_ONLY, then only string input may return True. if given NUMBER_ONLY, then only numeric input may return True. Giving None is equivalent to omitting this argument.

  • base (int, optional) – Follows the rules of Python’s built-in int(); see it’s documentation for your Python version. Ignored unless the input is of type str.

  • allow_underscores (bool, optional) – Underscores are allowed in numeric literals and in strings passed to int or float (see PEP 515 for details on what is and is not allowed). You can enable that behavior by setting this option to True - the default is False.

Returns

result – Whether or not the input is an int.

Return type

bool

Examples

>>> from fastnumbers import NUMBER_ONLY, STRING_ONLY, check_int
>>> check_int('56')
True
>>> check_int('56', consider=NUMBER_ONLY)
False
>>> check_int('56.07')
False
>>> check_int('56.07 lb')
False
>>> check_int('13af')
False
>>> check_int('13af', base=16)
True
>>> check_int('0x13af')
False
>>> check_int('0x13af', base=0)  # detect base from prefix
True
>>> check_int(56.07)
False
>>> check_int(56)
True
>>> check_int(56, consider=STRING_ONLY)
False

2.3.4. check_intlike()

fastnumbers.check_intlike(x, *, consider=None, allow_underscores=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 int 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 or int-like.

  • consider (optional) – Control the data types that may be interpreted. By default both string and numeric input may be considered. If given STRING_ONLY, then only string input may return True. if given NUMBER_ONLY, then only numeric input may return True. Giving None is equivalent to omitting this argument.

  • allow_underscores (bool, optional) – Underscores are allowed in numeric literals and in strings passed to int or float (see PEP 515 for details on what is and is not allowed). You can enable that behavior by setting this option to True - the default is False.

See also

try_forceint

Examples

>>> from fastnumbers import NUMBER_ONLY, STRING_ONLY, check_intlike
>>> check_intlike('56')
True
>>> check_intlike('56', consider=NUMBER_ONLY)
False
>>> check_intlike('56.07')
False
>>> check_intlike('56.0')
True
>>> check_intlike('56.07 lb')
False
>>> check_intlike(56.07)
False
>>> check_intlike(56.0)
True
>>> check_intlike(56.0, consider=STRING_ONLY)
False
>>> check_intlike(56)
True

2.3.5. query_type()

fastnumbers.query_type(x, *, allow_inf=False, allow_nan=False, coerce=False, allowed_types=*, allow_underscores=True)

Quickly determine the type that fastnumbers would return for a given input.

For string or bytes-like input, the contents of the string will be examined and the type int or float will be returned if the object contains a representation of an int or float, respectively. For all other cases, the type of the input object is returned, just like the built-in function type.

The input may be whitespace-padded.

Parameters
  • input – The input of which you wish to query the type fastnumbers might return.

  • allow_inf (bool, optional) – If True, then the strings ‘inf’ and ‘infinity’ will also return float. 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 float. This check is case-insensitive, and the string may be signed (i.e. ‘+/-‘). The default is False.

  • coerce (bool, optional) – If True, then numbers that are given as float but could be converted to an int without loss of precision will return type int instead of float.

  • allowed_types (sequence of types, optional) – If given, then only the given types may be returned, and anything else will return None.

  • allow_underscores (bool, optional) – Starting with Python 3.6, underscores are allowed in numeric literals and in strings passed to int or float (see PEP 515 for details on what is and is not allowed). You can disable that behavior by setting this option to False - the default is True.

Returns

result – The type that fastnumbers might return for the given input.

Return type

type

Examples

>>> from fastnumbers import query_type
>>> query_type('56')
<class 'int'>
>>> query_type('56.07')
<class 'float'>
>>> query_type('56.07 lb')
<class 'str'>
>>> query_type('56.07 lb', allowed_types=(float, int))  # returns None
>>> query_type('56.0')
<class 'float'>
>>> query_type('56.0', coerce=True)
<class 'int'>
>>> query_type(56.07)
<class 'float'>
>>> query_type(56)
<class 'int'>
>>> query_type('nan')
<class 'str'>
>>> query_type('nan', allow_nan=True)
<class 'float'>

2.4. Deprecated “Error-Handling” Functions

These functions have a less flexible interface than try_* functions, but otherwise do the same thing. New code should prefer the try_* functions instead, but the below functions will never be removed.

2.4.1. fast_real()

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

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

Identical in functionality to try_int() but with a different API that has the following differences:

  • allow_underscores is True by default, not False.

  • default=<some value> is replaced by on_fail=<some value>

  • raise_on_invalid=True is replaced by on_fail=RAISE

  • the function behaves as if on_type_error is set to RAISE and there is no way to modify this setting

2.4.2. fast_float()

fastnumbers.fast_float(x, default=None, *, raise_on_invalid=False, on_fail=None, nan=None, inf=None, allow_underscores=True)

(DEPRECATED) Quickly convert input to a float.

Identical in functionality to try_int() but with a different API that has the following differences:

  • allow_underscores is True by default, not False.

  • default=<some value> is replaced by on_fail=<some value>

  • raise_on_invalid=True is replaced by on_fail=RAISE

  • the function behaves as if on_type_error is set to RAISE and there is no way to modify this setting

2.4.3. fast_int()

fastnumbers.fast_int(x, default=None, *, raise_on_invalid=False, on_fail=None, base=10, allow_underscores=True)

(DEPRECATED) Quickly convert input to an int.

Identical in functionality to try_int() but with a different API that has the following differences:

  • allow_underscores is True by default, not False.

  • default=<some value> is replaced by on_fail=<some value>

  • raise_on_invalid=True is replaced by on_fail=RAISE

  • the function behaves as if on_type_error is set to RAISE and there is no way to modify this setting

2.4.4. fast_forceint()

fastnumbers.fast_forceint(x, default=None, *, raise_on_invalid=False, on_fail=None, allow_underscores=True)

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

Identical in functionality to try_forceint() but with a different API that has the following differences:

  • allow_underscores is True by default, not False.

  • default=<some value> is replaced by on_fail=<some value>

  • raise_on_invalid=True is replaced by on_fail=RAISE

  • the function behaves as if on_type_error is set to RAISE and there is no way to modify this setting

2.5. Deprecated “Checking” Functions

These functions have a less flexible interface than check_* functions, but otherwise do the same thing. New code should prefer the check_* functions instead, but the below functions will never be removed.

2.5.1. isreal()

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

(DEPRECATED) Quickly determine if a string is a real number.

Identical in functionality to check_real() but with a different API that has the following differences:

  • allow_underscores is True by default, not False.

  • instead of consider, there are two separate bool options str_only and num_only.

  • allow_nan is a bool that can only only tolggle behavior of “nan”; NaN will always return True.

  • allow_inf is a bool that can only only tolggle behavior of “inf”; INF will always return True.

2.5.2. isfloat()

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

(DEPRECATED) Quickly determine if a string is a float.

Identical in functionality to check_float() but with a different API that has the following differences:

  • allow_underscores is True by default, not False.

  • instead of consider, there are two separate bool options str_only and num_only.

  • allow_nan is a bool that can only only tolggle behavior of “nan”; NaN will always return True.

  • allow_inf is a bool that can only only tolggle behavior of “inf”; INF will always return True.

  • there is no strict option to toggle how strings containing integers are evaluated.

2.5.3. isint()

fastnumbers.isint(x, *, str_only=False, num_only=False, base=10, allow_underscores=True)

(DEPRECATED) Quickly determine if a string is an int.

Identical in functionality to check_int() but with a different API that has the following differences:

  • allow_underscores is True by default, not False.

  • instead of consider, there are two separate bool options str_only and num_only.

2.5.4. isintlike()

fastnumbers.isintlike(x, *, str_only=False, num_only=False, allow_underscores=True)

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

Identical in functionality to check_intlike() but with a different API that has the following differences:

  • allow_underscores is True by default, not False.

  • instead of consider, there are two separate bool options str_only and num_only.