0
# High-Performance Functions
1
2
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.
3
4
## Capabilities
5
6
### High-Speed Real Number Conversion
7
8
Ultra-fast conversion to integer or float with optional default values and custom transformation functions.
9
10
```python { .api }
11
def fast_real(
12
x,
13
default=None,
14
*,
15
raise_on_invalid=False,
16
inf=None,
17
nan=None,
18
on_fail=None,
19
key=None,
20
coerce=True,
21
allow_underscores=True
22
):
23
"""
24
High-speed conversion to int or float.
25
26
Parameters:
27
- x: Input to convert
28
- default: Default value to return on failure (positional)
29
- raise_on_invalid: Raise ValueError on invalid input (default: False)
30
- inf: Custom value for infinity (default: None, allows inf)
31
- nan: Custom value for NaN (default: None, allows nan)
32
- on_fail: Callable to transform input on failure
33
- key: Callable to transform input before conversion
34
- coerce: Coerce floats to ints when possible (default: True)
35
- allow_underscores: Allow underscores in numeric strings (default: True)
36
37
Returns:
38
- On success: int or float
39
- On failure: input, default value, or transformed result
40
"""
41
```
42
43
#### Usage Examples
44
45
```python
46
from fastnumbers import fast_real
47
48
# Basic high-speed conversion
49
fast_real('123') # 123 (int)
50
fast_real('123.45') # 123.45 (float)
51
fast_real('123.0') # 123 (int, coerced)
52
53
# Default value handling
54
fast_real('invalid', 0) # 0 (default value)
55
fast_real('123', 0) # 123 (conversion succeeds)
56
57
# Raise on invalid
58
fast_real('invalid', raise_on_invalid=True) # Raises ValueError
59
60
# Special value customization
61
fast_real('inf', inf=999.0) # 999.0 (custom inf)
62
fast_real('nan', nan=0.0) # 0.0 (custom nan)
63
64
# Key transformation
65
fast_real(' 123 ', key=str.strip) # 123 (stripped first)
66
fast_real(['1', '2', '3'], key=''.join) # 123
67
68
# Failure transformation
69
fast_real('invalid', on_fail=len) # 7 (length of 'invalid')
70
71
# Coercion control
72
fast_real('123.0', coerce=False) # 123.0 (float preserved)
73
74
# Underscore support (enabled by default)
75
fast_real('1_000_000') # 1000000
76
```
77
78
### High-Speed Float Conversion
79
80
Optimized float conversion with custom handling for special cases and transformation options.
81
82
```python { .api }
83
def fast_float(
84
x,
85
default=None,
86
*,
87
raise_on_invalid=False,
88
inf=None,
89
nan=None,
90
on_fail=None,
91
key=None,
92
allow_underscores=True
93
):
94
"""
95
High-speed conversion to float.
96
97
Parameters:
98
- x: Input to convert
99
- default: Default value to return on failure (positional)
100
- raise_on_invalid: Raise ValueError on invalid input (default: False)
101
- inf: Custom value for infinity (default: None, allows inf)
102
- nan: Custom value for NaN (default: None, allows nan)
103
- on_fail: Callable to transform input on failure
104
- key: Callable to transform input before conversion
105
- allow_underscores: Allow underscores in numeric strings (default: True)
106
107
Returns:
108
- On success: float
109
- On failure: input, default value, or transformed result
110
"""
111
```
112
113
#### Usage Examples
114
115
```python
116
from fastnumbers import fast_float
117
118
# High-speed float conversion
119
fast_float('123.45') # 123.45
120
fast_float(42) # 42.0
121
fast_float('1e5') # 100000.0
122
123
# Default handling
124
fast_float('invalid', 0.0) # 0.0
125
fast_float('invalid') # 'invalid' (no default)
126
127
# Scientific notation and formatting
128
fast_float('1.23e-4') # 0.000123
129
fast_float('1_234.567') # 1234.567
130
131
# Custom special value handling
132
fast_float('inf', inf=float('inf')) # inf (explicit)
133
fast_float('inf', inf=1e99) # 1e99 (custom large value)
134
fast_float('nan', nan=0.0) # 0.0 (nan replacement)
135
136
# Pre-processing with key
137
fast_float('$123.45', key=lambda x: x.lstrip('$')) # 123.45
138
```
139
140
### High-Speed Integer Conversion
141
142
Optimized integer conversion with base support and performance-focused parameter handling.
143
144
```python { .api }
145
def fast_int(
146
x,
147
default=None,
148
*,
149
raise_on_invalid=False,
150
base=None,
151
on_fail=None,
152
key=None,
153
allow_underscores=True
154
):
155
"""
156
High-speed conversion to int.
157
158
Parameters:
159
- x: Input to convert
160
- default: Default value to return on failure (positional)
161
- raise_on_invalid: Raise ValueError on invalid input (default: False)
162
- base: Number base for conversion (2-36, default: None for base-10)
163
- on_fail: Callable to transform input on failure
164
- key: Callable to transform input before conversion
165
- allow_underscores: Allow underscores in numeric strings (default: True)
166
167
Returns:
168
- On success: int
169
- On failure: input, default value, or transformed result
170
"""
171
```
172
173
#### Usage Examples
174
175
```python
176
from fastnumbers import fast_int
177
178
# High-speed integer conversion
179
fast_int('123') # 123
180
fast_int(456.0) # 456
181
fast_int('1_000') # 1000
182
183
# Default value
184
fast_int('invalid', -1) # -1
185
fast_int('123.45', 0) # 0 (can't convert float string)
186
187
# Base conversion
188
fast_int('ff', base=16) # 255
189
fast_int('1010', base=2) # 10
190
fast_int('777', base=8) # 511
191
192
# Preprocessing
193
fast_int('0x123', key=lambda x: x[2:], base=16) # 291
194
195
# Error handling
196
fast_int('invalid', raise_on_invalid=True) # Raises ValueError
197
fast_int('invalid', on_fail=lambda x: hash(x) % 1000) # Hash-based fallback
198
```
199
200
### High-Speed Forced Integer Conversion
201
202
Optimized integer conversion that truncates decimal parts, providing the fastest path to integer values.
203
204
```python { .api }
205
def fast_forceint(
206
x,
207
default=None,
208
*,
209
raise_on_invalid=False,
210
on_fail=None,
211
key=None,
212
allow_underscores=True
213
):
214
"""
215
High-speed forced conversion to int by truncating decimals.
216
217
Parameters:
218
- x: Input to convert
219
- default: Default value to return on failure (positional)
220
- raise_on_invalid: Raise ValueError on invalid input (default: False)
221
- on_fail: Callable to transform input on failure
222
- key: Callable to transform input before conversion
223
- allow_underscores: Allow underscores in numeric strings (default: True)
224
225
Returns:
226
- On success: int (truncated)
227
- On failure: input, default value, or transformed result
228
"""
229
```
230
231
#### Usage Examples
232
233
```python
234
from fastnumbers import fast_forceint
235
236
# Forced integer conversion with truncation
237
fast_forceint('123.89') # 123
238
fast_forceint(456.99) # 456
239
fast_forceint('-78.12') # -78
240
241
# Default handling
242
fast_forceint('invalid', 0) # 0
243
fast_forceint('123.45') # 123
244
245
# Compared to fast_int
246
fast_int('123.45', 0) # 0 (can't convert)
247
fast_forceint('123.45', 0) # 123 (truncated)
248
249
# Key transformation
250
fast_forceint('Price: $123.45', key=lambda x: x.split('$')[-1]) # 123
251
252
# High-performance truncation
253
fast_forceint(3.14159) # 3
254
fast_forceint(-2.71828) # -2
255
```
256
257
## Performance Characteristics
258
259
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:
260
261
- **C++ Implementation**: Core algorithms implemented in optimized C++
262
- **Minimal Overhead**: Streamlined parameter handling for common use cases
263
- **SIMD Optimizations**: Vectorized operations where possible
264
- **Branch Prediction**: Optimized control flow for common cases
265
266
## Parameter Patterns
267
268
### Positional Default Values
269
270
Unlike error-handling functions, high-performance functions accept default values as positional parameters for minimal overhead:
271
272
```python
273
# Error-handling pattern
274
result = try_float('invalid', on_fail=0.0)
275
276
# High-performance pattern
277
result = fast_float('invalid', 0.0)
278
```
279
280
### Key Transformations
281
282
The `key` parameter allows preprocessing input before conversion, enabling efficient data pipeline patterns:
283
284
```python
285
# Process and convert in one step
286
values = [fast_int(x, key=str.strip) for x in [' 123 ', ' 456 ']]
287
288
# Chain transformations
289
result = fast_float(data, key=lambda x: x.replace(',', ''))
290
```
291
292
### Failure Callbacks
293
294
The `on_fail` parameter accepts callables for custom failure handling:
295
296
```python
297
# Transform failures
298
result = fast_int('invalid', on_fail=lambda x: len(x))
299
300
# Logging with fallback
301
result = fast_float('bad', on_fail=lambda x: (log_error(x), 0.0)[1])
302
```
303
304
## Use Cases
305
306
High-performance functions are ideal for:
307
308
- **Data Processing Pipelines**: Maximum throughput for large datasets
309
- **Real-time Applications**: Minimal latency requirements
310
- **Scientific Computing**: Bulk numeric data conversion
311
- **Performance-Critical Code**: When every microsecond counts
312
- **Batch Processing**: Converting large numbers of values efficiently
313
314
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.