CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-fastnumbers

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.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

high-performance.mddocs/

High-Performance Functions

Optimized conversion functions that provide the fastest possible number conversion while maintaining flexibility through optional parameters. These functions are designed as high-performance alternatives to the error-handling functions, with different parameter patterns optimized for speed.

Capabilities

High-Speed Real Number Conversion

Ultra-fast conversion to integer or float with optional default values and custom transformation functions.

def fast_real(
    x,
    default=None,
    *,
    raise_on_invalid=False,
    inf=None,
    nan=None,
    on_fail=None,
    key=None,
    coerce=True,
    allow_underscores=True
):
    """
    High-speed conversion to int or float.

    Parameters:
    - x: Input to convert
    - default: Default value to return on failure (positional)
    - raise_on_invalid: Raise ValueError on invalid input (default: False)
    - inf: Custom value for infinity (default: None, allows inf)
    - nan: Custom value for NaN (default: None, allows nan)
    - on_fail: Callable to transform input on failure
    - key: Callable to transform input before conversion
    - coerce: Coerce floats to ints when possible (default: True)
    - allow_underscores: Allow underscores in numeric strings (default: True)

    Returns:
    - On success: int or float
    - On failure: input, default value, or transformed result
    """

Usage Examples

from fastnumbers import fast_real

# Basic high-speed conversion
fast_real('123')      # 123 (int)
fast_real('123.45')   # 123.45 (float)
fast_real('123.0')    # 123 (int, coerced)

# Default value handling
fast_real('invalid', 0)        # 0 (default value)
fast_real('123', 0)            # 123 (conversion succeeds)

# Raise on invalid
fast_real('invalid', raise_on_invalid=True)  # Raises ValueError

# Special value customization
fast_real('inf', inf=999.0)    # 999.0 (custom inf)
fast_real('nan', nan=0.0)      # 0.0 (custom nan)

# Key transformation
fast_real('  123  ', key=str.strip)  # 123 (stripped first)
fast_real(['1', '2', '3'], key=''.join)  # 123

# Failure transformation
fast_real('invalid', on_fail=len)  # 7 (length of 'invalid')

# Coercion control
fast_real('123.0', coerce=False)  # 123.0 (float preserved)

# Underscore support (enabled by default)
fast_real('1_000_000')  # 1000000

High-Speed Float Conversion

Optimized float conversion with custom handling for special cases and transformation options.

def fast_float(
    x,
    default=None,
    *,
    raise_on_invalid=False,
    inf=None,
    nan=None,
    on_fail=None,
    key=None,
    allow_underscores=True
):
    """
    High-speed conversion to float.

    Parameters:
    - x: Input to convert
    - default: Default value to return on failure (positional)
    - raise_on_invalid: Raise ValueError on invalid input (default: False)
    - inf: Custom value for infinity (default: None, allows inf)
    - nan: Custom value for NaN (default: None, allows nan)
    - on_fail: Callable to transform input on failure
    - key: Callable to transform input before conversion
    - allow_underscores: Allow underscores in numeric strings (default: True)

    Returns:
    - On success: float
    - On failure: input, default value, or transformed result
    """

Usage Examples

from fastnumbers import fast_float

# High-speed float conversion
fast_float('123.45')    # 123.45
fast_float(42)          # 42.0
fast_float('1e5')       # 100000.0

# Default handling
fast_float('invalid', 0.0)     # 0.0
fast_float('invalid')          # 'invalid' (no default)

# Scientific notation and formatting
fast_float('1.23e-4')          # 0.000123
fast_float('1_234.567')        # 1234.567

# Custom special value handling
fast_float('inf', inf=float('inf'))  # inf (explicit)
fast_float('inf', inf=1e99)          # 1e99 (custom large value)
fast_float('nan', nan=0.0)           # 0.0 (nan replacement)

# Pre-processing with key
fast_float('$123.45', key=lambda x: x.lstrip('$'))  # 123.45

High-Speed Integer Conversion

Optimized integer conversion with base support and performance-focused parameter handling.

def fast_int(
    x,
    default=None,
    *,
    raise_on_invalid=False,
    base=None,
    on_fail=None,
    key=None,
    allow_underscores=True
):
    """
    High-speed conversion to int.

    Parameters:
    - x: Input to convert
    - default: Default value to return on failure (positional)
    - raise_on_invalid: Raise ValueError on invalid input (default: False)
    - base: Number base for conversion (2-36, default: None for base-10)
    - on_fail: Callable to transform input on failure
    - key: Callable to transform input before conversion
    - allow_underscores: Allow underscores in numeric strings (default: True)

    Returns:
    - On success: int
    - On failure: input, default value, or transformed result
    """

Usage Examples

from fastnumbers import fast_int

# High-speed integer conversion
fast_int('123')        # 123
fast_int(456.0)        # 456
fast_int('1_000')      # 1000

# Default value
fast_int('invalid', -1)        # -1
fast_int('123.45', 0)          # 0 (can't convert float string)

# Base conversion
fast_int('ff', base=16)        # 255
fast_int('1010', base=2)       # 10
fast_int('777', base=8)        # 511

# Preprocessing
fast_int('0x123', key=lambda x: x[2:], base=16)  # 291

# Error handling
fast_int('invalid', raise_on_invalid=True)  # Raises ValueError
fast_int('invalid', on_fail=lambda x: hash(x) % 1000)  # Hash-based fallback

High-Speed Forced Integer Conversion

Optimized integer conversion that truncates decimal parts, providing the fastest path to integer values.

def fast_forceint(
    x,
    default=None,
    *,
    raise_on_invalid=False,
    on_fail=None,
    key=None,
    allow_underscores=True
):
    """
    High-speed forced conversion to int by truncating decimals.

    Parameters:
    - x: Input to convert
    - default: Default value to return on failure (positional)
    - raise_on_invalid: Raise ValueError on invalid input (default: False)
    - on_fail: Callable to transform input on failure
    - key: Callable to transform input before conversion
    - allow_underscores: Allow underscores in numeric strings (default: True)

    Returns:
    - On success: int (truncated)
    - On failure: input, default value, or transformed result
    """

Usage Examples

from fastnumbers import fast_forceint

# Forced integer conversion with truncation
fast_forceint('123.89')    # 123
fast_forceint(456.99)      # 456
fast_forceint('-78.12')    # -78

# Default handling
fast_forceint('invalid', 0)      # 0
fast_forceint('123.45')          # 123

# Compared to fast_int
fast_int('123.45', 0)            # 0 (can't convert)
fast_forceint('123.45', 0)       # 123 (truncated)

# Key transformation
fast_forceint('Price: $123.45', key=lambda x: x.split('$')[-1])  # 123

# High-performance truncation
fast_forceint(3.14159)           # 3
fast_forceint(-2.71828)          # -2

Performance Characteristics

These functions are optimized for maximum speed and are significantly faster than both Python's built-in conversion functions and the try_* error-handling functions:

  • C++ Implementation: Core algorithms implemented in optimized C++
  • Minimal Overhead: Streamlined parameter handling for common use cases
  • SIMD Optimizations: Vectorized operations where possible
  • Branch Prediction: Optimized control flow for common cases

Parameter Patterns

Positional Default Values

Unlike error-handling functions, high-performance functions accept default values as positional parameters for minimal overhead:

# Error-handling pattern
result = try_float('invalid', on_fail=0.0)

# High-performance pattern  
result = fast_float('invalid', 0.0)

Key Transformations

The key parameter allows preprocessing input before conversion, enabling efficient data pipeline patterns:

# Process and convert in one step
values = [fast_int(x, key=str.strip) for x in ['  123  ', ' 456 ']]

# Chain transformations
result = fast_float(data, key=lambda x: x.replace(',', ''))

Failure Callbacks

The on_fail parameter accepts callables for custom failure handling:

# Transform failures
result = fast_int('invalid', on_fail=lambda x: len(x))

# Logging with fallback
result = fast_float('bad', on_fail=lambda x: (log_error(x), 0.0)[1])

Use Cases

High-performance functions are ideal for:

  • Data Processing Pipelines: Maximum throughput for large datasets
  • Real-time Applications: Minimal latency requirements
  • Scientific Computing: Bulk numeric data conversion
  • Performance-Critical Code: When every microsecond counts
  • Batch Processing: Converting large numbers of values efficiently

Choose high-performance functions when speed is the primary concern and the simpler parameter model meets your needs. For more complex error handling requirements, use the try_* functions instead.

Install with Tessl CLI

npx tessl i tessl/pypi-fastnumbers

docs

builtin-replacements.md

checking.md

error-handling.md

high-performance.md

index.md

utilities.md

tile.json