0
# fastnumbers
1
2
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. The library provides three main categories of functionality: error-handling functions for robust conversion with customizable fallback behaviors, checking functions for validating numeric convertibility, and optimized drop-in replacements for Python's built-in `int()` and `float()` functions.
3
4
## Package Information
5
6
- **Package Name**: fastnumbers
7
- **Language**: Python
8
- **Installation**: `pip install fastnumbers`
9
- **Version**: 4.0.1
10
11
## Core Imports
12
13
```python
14
import fastnumbers
15
```
16
17
Common usage patterns:
18
19
```python
20
from fastnumbers import try_float, try_int, try_real, try_forceint
21
from fastnumbers import check_float, check_int, check_real, check_intlike
22
from fastnumbers import fast_real, fast_float, fast_int, fast_forceint
23
from fastnumbers import int, float, real, query_type
24
from fastnumbers import RAISE, INPUT, ALLOWED, DISALLOWED, STRING_ONLY, NUMBER_ONLY
25
from fastnumbers import __version__
26
```
27
28
For legacy compatibility:
29
30
```python
31
from fastnumbers import isfloat, isint, isintlike, isreal # Deprecated
32
```
33
34
## Basic Usage
35
36
```python
37
from fastnumbers import try_float, try_int, check_real, RAISE
38
39
# Error-handling conversion with default fallback
40
result = try_float('123.45') # Returns 123.45
41
result = try_float('invalid') # Returns 'invalid' (input as-is)
42
43
# Error-handling conversion with custom fallback
44
result = try_float('invalid', on_fail=0.0) # Returns 0.0
45
result = try_int('42', on_fail=RAISE) # Raises ValueError if invalid
46
47
# High-speed checking before conversion
48
if check_real('123.45'):
49
value = float('123.45')
50
51
# Unicode numeric characters supported
52
result = try_float('\u2164') # Roman numeral V -> 5.0
53
result = try_int('\u2466') # Circled 7 -> 7
54
```
55
56
## Architecture
57
58
fastnumbers is implemented in C++ with Python bindings for maximum performance. The library uses a hierarchical approach:
59
60
- **Selector Constants**: Control function behavior (RAISE, INPUT, ALLOWED, etc.)
61
- **Type System**: Extensive use of overloads and generic types for flexible return types
62
- **Error Handling**: Multiple strategies for handling conversion failures and type errors
63
- **Unicode Support**: Full support for Unicode numeric characters and various number formats
64
65
The architecture leverages optimized C++ algorithms including fast_float for float conversions and heuristic-based integer parsing, making it significantly faster than Python's built-in conversion functions while maintaining compatibility and adding flexibility.
66
67
## Capabilities
68
69
### Error-Handling Functions
70
71
Robust number conversion functions with customizable error handling, supporting various fallback strategies including returning input as-is, providing default values, calling transformation functions, or raising exceptions.
72
73
```python { .api }
74
def try_real(x, *, inf=ALLOWED, nan=ALLOWED, on_fail=INPUT, on_type_error=RAISE, coerce=True, allow_underscores=False): ...
75
def try_float(x, *, inf=ALLOWED, nan=ALLOWED, on_fail=INPUT, on_type_error=RAISE, allow_underscores=False): ...
76
def try_int(x, *, on_fail=INPUT, on_type_error=RAISE, base=10, allow_underscores=False): ...
77
def try_forceint(x, *, on_fail=INPUT, on_type_error=RAISE, allow_underscores=False): ...
78
```
79
80
[Error-Handling Functions](./error-handling.md)
81
82
### Checking Functions
83
84
Validation functions to test whether inputs can be converted to specific numeric types without performing the actual conversion, enabling conditional processing and input validation.
85
86
```python { .api }
87
def check_real(x, *, consider=None, inf=NUMBER_ONLY, nan=NUMBER_ONLY, allow_underscores=False) -> bool: ...
88
def check_float(x, *, consider=None, inf=NUMBER_ONLY, nan=NUMBER_ONLY, strict=False, allow_underscores=False) -> bool: ...
89
def check_int(x, *, consider=None, base=0, allow_underscores=False) -> bool: ...
90
def check_intlike(x, *, consider=None, allow_underscores=False) -> bool: ...
91
```
92
93
[Checking Functions](./checking.md)
94
95
### High-Performance Functions
96
97
Optimized drop-in replacement functions that provide the same functionality as Python's built-in conversion functions but with significantly better performance and additional features like custom default values and key transformations.
98
99
```python { .api }
100
def fast_real(x, default=None, *, raise_on_invalid=False, inf=None, nan=None, on_fail=None, key=None, coerce=True, allow_underscores=True): ...
101
def fast_float(x, default=None, *, raise_on_invalid=False, inf=None, nan=None, on_fail=None, key=None, allow_underscores=True): ...
102
def fast_int(x, default=None, *, raise_on_invalid=False, base=None, on_fail=None, key=None, allow_underscores=True): ...
103
def fast_forceint(x, default=None, *, raise_on_invalid=False, on_fail=None, key=None, allow_underscores=True): ...
104
```
105
106
[High-Performance Functions](./high-performance.md)
107
108
### Built-in Replacements
109
110
Direct drop-in replacements for Python's built-in `int()`, `float()`, and additional `real()` function that behave identically to the originals but with improved performance characteristics.
111
112
```python { .api }
113
def int(x=0, base=10): ...
114
def float(x=0.0): ...
115
def real(x=0.0, *, coerce=True): ...
116
```
117
118
[Built-in Replacements](./builtin-replacements.md)
119
120
### Utility Functions
121
122
Additional utility functions for type analysis and deprecated functions maintained for backward compatibility.
123
124
```python { .api }
125
def query_type(x, *, allow_inf=False, allow_nan=False, coerce=False, allowed_types=None, allow_underscores=False): ...
126
```
127
128
[Utility Functions](./utilities.md)
129
130
## Types
131
132
### Selector Constants
133
134
```python { .api }
135
ALLOWED: ALLOWED_T # Allow inf/nan values
136
DISALLOWED: DISALLOWED_T # Disallow inf/nan values
137
INPUT: INPUT_T # Return input as-is on failure
138
RAISE: RAISE_T # Raise exception on failure
139
STRING_ONLY: STRING_ONLY_T # Consider only string types
140
NUMBER_ONLY: NUMBER_ONLY_T # Consider only numeric types
141
142
# Type aliases for parameter types
143
ConsiderType = Union[STRING_ONLY_T, NUMBER_ONLY_T, None]
144
InfNanCheckType = Union[STRING_ONLY_T, NUMBER_ONLY_T, ALLOWED_T, DISALLOWED_T]
145
```
146
147
### Input Types
148
149
```python { .api }
150
from typing import Union, TypeVar
151
from typing_extensions import Protocol
152
153
# Protocol types for duck typing
154
class HasIndex(Protocol):
155
def __index__(self) -> int: ...
156
157
class HasInt(Protocol):
158
def __int__(self) -> int: ...
159
160
class ItWillFloat(Protocol):
161
def __float__(self) -> float: ...
162
163
# Union of all acceptable input types
164
InputType = Union[int, float, str, bytes, bytearray, HasIndex, HasInt, ItWillFloat]
165
FastInputType = TypeVar("FastInputType", int, float, ItWillFloat, HasIndex, HasInt, str, bytes, bytearray)
166
AnyInputType = TypeVar("AnyInputType")
167
```
168
169
### Version Information
170
171
```python { .api }
172
__version__: str # Package version string
173
```
174
175
## Error Handling Patterns
176
177
All `try_*` functions support multiple error handling strategies:
178
179
- **`INPUT`** (default): Return the original input unchanged
180
- **`RAISE`**: Raise a ValueError with descriptive message
181
- **Custom value**: Return any specified default value
182
- **Callable**: Call a function with the input and return its result
183
184
The `on_type_error` parameter handles cases where the input type is completely invalid (default: `RAISE`), while `on_fail` handles conversion failures (default: `INPUT`).