Super-fast and clean conversions to numbers with flexible error handling and high-performance drop-in replacements for Python's built-in number conversion functions.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Robust number conversion functions with comprehensive error handling capabilities. These functions provide flexible strategies for dealing with conversion failures, type errors, and special floating-point values like infinity and NaN.
Converts input to either an integer or float depending on the value, with optional coercion control to force float-to-int conversion when the result would be a whole number.
# Multiple overloads exist - simplified signature shown
def try_real(
x: InputType,
*,
inf: Union[ALLOWED_T, INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = ALLOWED,
nan: Union[ALLOWED_T, INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = ALLOWED,
on_fail: Union[INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = INPUT,
on_type_error: Union[INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = RAISE,
coerce: bool = True,
allow_underscores: bool = False
) -> Union[int, float, InputType, Any]:
"""
Convert input to int or float with error handling.
Parameters:
- x: Input to convert (str, int, float, bytes, etc.)
- inf: How to handle infinity values (ALLOWED, INPUT, RAISE, or custom value/callable)
- nan: How to handle NaN values (ALLOWED, INPUT, RAISE, or custom value/callable)
- on_fail: What to do on conversion failure (INPUT, RAISE, custom value, or callable)
- on_type_error: What to do on type error (RAISE, INPUT, custom value, or callable)
- coerce: Whether to coerce floats to ints when possible (default: True)
- allow_underscores: Allow underscores in numeric strings (default: False)
Returns:
- On success: int or float
- On failure: depends on on_fail parameter
Note: This function has many overloads for precise typing based on parameter combinations.
"""from fastnumbers import try_real, INPUT, RAISE
# Basic conversion
try_real('123') # 123 (int)
try_real('123.0') # 123 (int, coerced)
try_real('123.45') # 123.45 (float)
try_real(123.0) # 123 (int, coerced)
# Coercion control
try_real('123.0', coerce=False) # 123.0 (float, not coerced)
# Error handling
try_real('invalid') # 'invalid' (INPUT default)
try_real('invalid', on_fail=0) # 0 (custom default)
try_real('invalid', on_fail=RAISE) # Raises ValueError
try_real('invalid', on_fail=len) # 7 (callable result)
# Special value handling
try_real('inf') # inf (ALLOWED default)
try_real('inf', inf=0.0) # 0.0 (custom replacement)
try_real('nan', nan=RAISE) # Raises ValueError
# Unicode support
try_real('\u2164') # 5.0 (Roman numeral V)
try_real('\u2466') # 7 (circled 7)Converts input to float with comprehensive error handling for conversion failures and special floating-point values.
# Multiple overloads exist - simplified signature shown
def try_float(
x: InputType,
*,
inf: Union[ALLOWED_T, INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = ALLOWED,
nan: Union[ALLOWED_T, INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = ALLOWED,
on_fail: Union[INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = INPUT,
on_type_error: Union[INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = RAISE,
allow_underscores: bool = False
) -> Union[float, InputType, Any]:
"""
Convert input to float with error handling.
Parameters:
- x: Input to convert (str, int, float, bytes, etc.)
- inf: How to handle infinity values (ALLOWED, INPUT, RAISE, or custom value/callable)
- nan: How to handle NaN values (ALLOWED, INPUT, RAISE, or custom value/callable)
- on_fail: What to do on conversion failure (INPUT, RAISE, custom value, or callable)
- on_type_error: What to do on type error (RAISE, INPUT, custom value, or callable)
- allow_underscores: Allow underscores in numeric strings (default: False)
Returns:
- On success: float
- On failure: depends on on_fail parameter
Note: This function has many overloads for precise typing based on parameter combinations.
"""from fastnumbers import try_float, ALLOWED, DISALLOWED
# Basic conversion
try_float('123.45') # 123.45
try_float(42) # 42.0
try_float('1e5') # 100000.0
# Special values
try_float('inf') # inf
try_float('inf', inf=DISALLOWED) # 'inf' (returned as-is)
try_float('nan', nan=999.0) # 999.0
# Scientific notation and formatting
try_float('1.23e-4') # 0.000123
try_float(' 42.5 ') # 42.5 (whitespace handled)
try_float('1_000.5', allow_underscores=True) # 1000.5Converts input to integer with support for different number bases and comprehensive error handling.
# Multiple overloads exist - simplified signature shown
def try_int(
x: InputType,
*,
on_fail: Union[INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = INPUT,
on_type_error: Union[INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = RAISE,
base: Union[int, HasIndex] = 10,
allow_underscores: bool = False
) -> Union[int, InputType, Any]:
"""
Convert input to int with error handling.
Parameters:
- x: Input to convert (str, int, float, bytes, etc.)
- on_fail: What to do on conversion failure (INPUT, RAISE, custom value, or callable)
- on_type_error: What to do on type error (RAISE, INPUT, custom value, or callable)
- base: Number base for conversion (2-36, default: 10)
- allow_underscores: Allow underscores in numeric strings (default: False)
Returns:
- On success: int
- On failure: depends on on_fail parameter
Note: This function has many overloads for precise typing based on parameter combinations.
"""from fastnumbers import try_int
# Basic conversion
try_int('123') # 123
try_int(123.0) # 123
try_int('123.0') # ValueError (not a valid int string)
# Base conversion
try_int('ff', base=16) # 255
try_int('1010', base=2) # 10
try_int('777', base=8) # 511
# Error handling
try_int('123.45') # '123.45' (INPUT default)
try_int('123.45', on_fail=-1) # -1
try_int('invalid', on_fail=RAISE) # Raises ValueError
# Unicode and formatting
try_int('\u2466') # 7 (circled 7)
try_int('1_000', allow_underscores=True) # 1000Converts input to integer by truncating decimal parts, useful for forcing float values to integers.
# Multiple overloads exist - simplified signature shown
def try_forceint(
x: InputType,
*,
on_fail: Union[INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = INPUT,
on_type_error: Union[INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = RAISE,
allow_underscores: bool = False
) -> Union[int, InputType, Any]:
"""
Force conversion to int by truncating decimal parts.
Parameters:
- x: Input to convert (str, int, float, bytes, etc.)
- on_fail: What to do on conversion failure (INPUT, RAISE, custom value, or callable)
- on_type_error: What to do on type error (RAISE, INPUT, custom value, or callable)
- allow_underscores: Allow underscores in numeric strings (default: False)
Returns:
- On success: int (truncated)
- On failure: depends on on_fail parameter
Note: This function has many overloads for precise typing based on parameter combinations.
"""from fastnumbers import try_forceint
# Truncation behavior
try_forceint('123.89') # 123 (truncated)
try_forceint(456.99) # 456 (truncated)
try_forceint('-78.12') # -78 (truncated)
# Compared to try_int
try_int('123.45') # '123.45' (can't convert)
try_forceint('123.45') # 123 (truncated)
# Error handling
try_forceint('invalid') # 'invalid' (INPUT default)
try_forceint('invalid', on_fail=0) # 0
try_forceint('invalid', on_fail=RAISE) # Raises ValueErrorAll error-handling functions support multiple strategies for dealing with failures:
INPUT (default): Return the original input unchangedRAISE: Raise ValueError with descriptive error messageRAISE (default): Raise TypeError for invalid input typesINPUT: Return the original input unchangedALLOWED (default): Allow inf/nan values through unchangedINPUT: Return original string representationRAISE: Raise ValueError for inf/nan valuesAll functions use extensive type overloads to provide accurate return type information based on the parameters used, enabling proper static type checking and IDE support.
Install with Tessl CLI
npx tessl i tessl/pypi-fastnumbers