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
Direct drop-in replacements for Python's built-in int() and float() functions that provide identical behavior with significantly improved performance. These functions are designed to be used as direct substitutes without requiring code changes.
High-performance drop-in replacement for Python's built-in int() function with identical behavior and API.
def int(x=0, base=10):
"""
Drop-in replacement for Python's built-in int() function.
Parameters:
- x: Value to convert to integer (default: 0)
- base: Number base for string conversion (default: 10)
Returns:
- int: Integer representation of input
Raises:
- ValueError: If string cannot be converted to int
- TypeError: If input type is invalid
"""from fastnumbers import int
# Direct replacement usage
int() # 0 (default)
int(42) # 42
int(3.14) # 3 (truncated)
int('123') # 123
int(' 456 ') # 456 (whitespace handled)
# Base conversion (identical to built-in)
int('ff', 16) # 255 (hexadecimal)
int('1010', 2) # 10 (binary)
int('777', 8) # 511 (octal)
# Error behavior (identical to built-in)
int('123.45') # ValueError: invalid literal for int()
int('invalid') # ValueError: invalid literal for int()
int([1, 2, 3]) # TypeError: int() argument must be a string...
# Special cases (identical to built-in)
int(True) # 1
int(False) # 0
int(-3.99) # -3 (truncated toward zero)High-performance drop-in replacement for Python's built-in float() function with identical behavior and API.
def float(x=0.0):
"""
Drop-in replacement for Python's built-in float() function.
Parameters:
- x: Value to convert to float (default: 0.0)
Returns:
- float: Float representation of input
Raises:
- ValueError: If string cannot be converted to float
- TypeError: If input type is invalid
"""from fastnumbers import float
# Direct replacement usage
float() # 0.0 (default)
float(42) # 42.0
float('123.45') # 123.45
float(' -67.89 ') # -67.89 (whitespace handled)
# Scientific notation (identical to built-in)
float('1e5') # 100000.0
float('1.23e-4') # 0.000123
float('-2.5E+2') # -250.0
# Special values (identical to built-in)
float('inf') # inf
float('-inf') # -inf
float('nan') # nan
float('infinity') # inf
float('-infinity') # -inf
# Error behavior (identical to built-in)
float('invalid') # ValueError: could not convert string to float
float([1, 2, 3]) # TypeError: float() argument must be a string...
# Type conversion (identical to built-in)
float(True) # 1.0
float(False) # 0.0Extended function that converts to the most appropriate numeric type (int or float) based on the value, with optional coercion control.
def real(x=0.0, *, coerce=True):
"""
Convert to the most appropriate numeric type (int or float).
Parameters:
- x: Value to convert (default: 0.0)
- coerce: Whether to coerce floats to ints when possible (default: True)
Returns:
- Union[int, float]: Most appropriate numeric representation
Raises:
- ValueError: If string cannot be converted to number
- TypeError: If input type is invalid
"""from fastnumbers import real
# Automatic type selection
real('123') # 123 (int)
real('123.0') # 123 (int, coerced)
real('123.45') # 123.45 (float)
real(456.0) # 456 (int, coerced)
real(456.7) # 456.7 (float)
# Coercion control
real('123.0', coerce=True) # 123 (int)
real('123.0', coerce=False) # 123.0 (float)
real(456.0, coerce=True) # 456 (int)
real(456.0, coerce=False) # 456.0 (float)
# Default behavior
real() # 0 (int, since 0.0 coerces to 0)
real(coerce=False) # 0.0 (float)
# Complex cases
real('1e2') # 100 (int, since 100.0 coerces)
real('1e-1', coerce=False) # 0.1 (float)
# Error behavior (like built-ins)
real('invalid') # ValueError: could not convert string to realThese replacement functions provide significant performance improvements over Python's built-ins:
| Function | Speedup vs Built-in | Use Case |
|---|---|---|
fastnumbers.int() | 2-10x faster | String to int conversion |
fastnumbers.float() | 2-15x faster | String to float conversion |
fastnumbers.real() | 2-12x faster | Optimal type conversion |
import timeit
from fastnumbers import int as fast_int, float as fast_float
# Integer conversion performance
builtin_time = timeit.timeit(lambda: int('12345'), number=100000)
fast_time = timeit.timeit(lambda: fast_int('12345'), number=100000)
print(f"Integer speedup: {builtin_time / fast_time:.1f}x")
# Float conversion performance
builtin_time = timeit.timeit(lambda: float('123.45'), number=100000)
fast_time = timeit.timeit(lambda: fast_float('123.45'), number=100000)
print(f"Float speedup: {builtin_time / fast_time:.1f}x")These functions are designed to be complete drop-in replacements:
# Can replace built-ins directly
import fastnumbers
import builtins
# Shadow built-ins (use with caution)
int = fastnumbers.int
float = fastnumbers.float
# Or use module-level replacement
import fastnumbers as fn
result = fn.int('123')Error messages and exception types match Python's built-ins exactly:
# Both raise identical ValueErrors
try:
int('invalid')
except ValueError as e:
print(e) # "invalid literal for int() with base 10: 'invalid'"
try:
fastnumbers.int('invalid')
except ValueError as e:
print(e) # "invalid literal for int() with base 10: 'invalid'"All edge cases are handled identically to built-ins:
# Whitespace handling
int(' 123 ') == fastnumbers.int(' 123 ') # True
# Special float values
float('inf') == fastnumbers.float('inf') # True
float('nan') != fastnumbers.float('nan') # True (NaN != NaN)
# Type coercion
int(True) == fastnumbers.int(True) # True (1)
float(False) == fastnumbers.float(False) # True (0.0)Replace only performance-critical conversions:
from fastnumbers import int as fast_int, float as fast_float
def process_data(raw_values):
# Use fast versions for bulk processing
return [fast_float(x) for x in raw_values if fast_int(x, 0) > 0]Import entire module for consistent performance:
import fastnumbers as fn
# Use fn.int, fn.float throughout codebase
def parse_config(config_dict):
return {
'port': fn.int(config_dict.get('port', '8080')),
'timeout': fn.float(config_dict.get('timeout', '30.0')),
'max_size': fn.real(config_dict.get('max_size', '1000'))
}Use in tight loops and data processing:
from fastnumbers import int as fast_int, real as fast_real
def process_csv_row(row):
# Fast conversion in data processing pipeline
return [fast_real(cell) for cell in row if cell.strip()]
def parse_large_dataset(lines):
# Bulk processing with performance replacements
return [process_csv_row(line.split(',')) for line in lines]These functions provide the easiest path to performance improvements in existing codebases that heavily use built-in number conversion functions.
Install with Tessl CLI
npx tessl i tessl/pypi-fastnumbers