0
# Error-Handling Functions
1
2
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.
3
4
## Capabilities
5
6
### Real Number Conversion
7
8
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.
9
10
```python { .api }
11
# Multiple overloads exist - simplified signature shown
12
def try_real(
13
x: InputType,
14
*,
15
inf: Union[ALLOWED_T, INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = ALLOWED,
16
nan: Union[ALLOWED_T, INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = ALLOWED,
17
on_fail: Union[INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = INPUT,
18
on_type_error: Union[INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = RAISE,
19
coerce: bool = True,
20
allow_underscores: bool = False
21
) -> Union[int, float, InputType, Any]:
22
"""
23
Convert input to int or float with error handling.
24
25
Parameters:
26
- x: Input to convert (str, int, float, bytes, etc.)
27
- inf: How to handle infinity values (ALLOWED, INPUT, RAISE, or custom value/callable)
28
- nan: How to handle NaN values (ALLOWED, INPUT, RAISE, or custom value/callable)
29
- on_fail: What to do on conversion failure (INPUT, RAISE, custom value, or callable)
30
- on_type_error: What to do on type error (RAISE, INPUT, custom value, or callable)
31
- coerce: Whether to coerce floats to ints when possible (default: True)
32
- allow_underscores: Allow underscores in numeric strings (default: False)
33
34
Returns:
35
- On success: int or float
36
- On failure: depends on on_fail parameter
37
38
Note: This function has many overloads for precise typing based on parameter combinations.
39
"""
40
```
41
42
#### Usage Examples
43
44
```python
45
from fastnumbers import try_real, INPUT, RAISE
46
47
# Basic conversion
48
try_real('123') # 123 (int)
49
try_real('123.0') # 123 (int, coerced)
50
try_real('123.45') # 123.45 (float)
51
try_real(123.0) # 123 (int, coerced)
52
53
# Coercion control
54
try_real('123.0', coerce=False) # 123.0 (float, not coerced)
55
56
# Error handling
57
try_real('invalid') # 'invalid' (INPUT default)
58
try_real('invalid', on_fail=0) # 0 (custom default)
59
try_real('invalid', on_fail=RAISE) # Raises ValueError
60
try_real('invalid', on_fail=len) # 7 (callable result)
61
62
# Special value handling
63
try_real('inf') # inf (ALLOWED default)
64
try_real('inf', inf=0.0) # 0.0 (custom replacement)
65
try_real('nan', nan=RAISE) # Raises ValueError
66
67
# Unicode support
68
try_real('\u2164') # 5.0 (Roman numeral V)
69
try_real('\u2466') # 7 (circled 7)
70
```
71
72
### Float Conversion
73
74
Converts input to float with comprehensive error handling for conversion failures and special floating-point values.
75
76
```python { .api }
77
# Multiple overloads exist - simplified signature shown
78
def try_float(
79
x: InputType,
80
*,
81
inf: Union[ALLOWED_T, INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = ALLOWED,
82
nan: Union[ALLOWED_T, INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = ALLOWED,
83
on_fail: Union[INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = INPUT,
84
on_type_error: Union[INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = RAISE,
85
allow_underscores: bool = False
86
) -> Union[float, InputType, Any]:
87
"""
88
Convert input to float with error handling.
89
90
Parameters:
91
- x: Input to convert (str, int, float, bytes, etc.)
92
- inf: How to handle infinity values (ALLOWED, INPUT, RAISE, or custom value/callable)
93
- nan: How to handle NaN values (ALLOWED, INPUT, RAISE, or custom value/callable)
94
- on_fail: What to do on conversion failure (INPUT, RAISE, custom value, or callable)
95
- on_type_error: What to do on type error (RAISE, INPUT, custom value, or callable)
96
- allow_underscores: Allow underscores in numeric strings (default: False)
97
98
Returns:
99
- On success: float
100
- On failure: depends on on_fail parameter
101
102
Note: This function has many overloads for precise typing based on parameter combinations.
103
"""
104
```
105
106
#### Usage Examples
107
108
```python
109
from fastnumbers import try_float, ALLOWED, DISALLOWED
110
111
# Basic conversion
112
try_float('123.45') # 123.45
113
try_float(42) # 42.0
114
try_float('1e5') # 100000.0
115
116
# Special values
117
try_float('inf') # inf
118
try_float('inf', inf=DISALLOWED) # 'inf' (returned as-is)
119
try_float('nan', nan=999.0) # 999.0
120
121
# Scientific notation and formatting
122
try_float('1.23e-4') # 0.000123
123
try_float(' 42.5 ') # 42.5 (whitespace handled)
124
try_float('1_000.5', allow_underscores=True) # 1000.5
125
```
126
127
### Integer Conversion
128
129
Converts input to integer with support for different number bases and comprehensive error handling.
130
131
```python { .api }
132
# Multiple overloads exist - simplified signature shown
133
def try_int(
134
x: InputType,
135
*,
136
on_fail: Union[INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = INPUT,
137
on_type_error: Union[INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = RAISE,
138
base: Union[int, HasIndex] = 10,
139
allow_underscores: bool = False
140
) -> Union[int, InputType, Any]:
141
"""
142
Convert input to int with error handling.
143
144
Parameters:
145
- x: Input to convert (str, int, float, bytes, etc.)
146
- on_fail: What to do on conversion failure (INPUT, RAISE, custom value, or callable)
147
- on_type_error: What to do on type error (RAISE, INPUT, custom value, or callable)
148
- base: Number base for conversion (2-36, default: 10)
149
- allow_underscores: Allow underscores in numeric strings (default: False)
150
151
Returns:
152
- On success: int
153
- On failure: depends on on_fail parameter
154
155
Note: This function has many overloads for precise typing based on parameter combinations.
156
"""
157
```
158
159
#### Usage Examples
160
161
```python
162
from fastnumbers import try_int
163
164
# Basic conversion
165
try_int('123') # 123
166
try_int(123.0) # 123
167
try_int('123.0') # ValueError (not a valid int string)
168
169
# Base conversion
170
try_int('ff', base=16) # 255
171
try_int('1010', base=2) # 10
172
try_int('777', base=8) # 511
173
174
# Error handling
175
try_int('123.45') # '123.45' (INPUT default)
176
try_int('123.45', on_fail=-1) # -1
177
try_int('invalid', on_fail=RAISE) # Raises ValueError
178
179
# Unicode and formatting
180
try_int('\u2466') # 7 (circled 7)
181
try_int('1_000', allow_underscores=True) # 1000
182
```
183
184
### Forced Integer Conversion
185
186
Converts input to integer by truncating decimal parts, useful for forcing float values to integers.
187
188
```python { .api }
189
# Multiple overloads exist - simplified signature shown
190
def try_forceint(
191
x: InputType,
192
*,
193
on_fail: Union[INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = INPUT,
194
on_type_error: Union[INPUT_T, RAISE_T, Any, Callable[[InputType], Any]] = RAISE,
195
allow_underscores: bool = False
196
) -> Union[int, InputType, Any]:
197
"""
198
Force conversion to int by truncating decimal parts.
199
200
Parameters:
201
- x: Input to convert (str, int, float, bytes, etc.)
202
- on_fail: What to do on conversion failure (INPUT, RAISE, custom value, or callable)
203
- on_type_error: What to do on type error (RAISE, INPUT, custom value, or callable)
204
- allow_underscores: Allow underscores in numeric strings (default: False)
205
206
Returns:
207
- On success: int (truncated)
208
- On failure: depends on on_fail parameter
209
210
Note: This function has many overloads for precise typing based on parameter combinations.
211
"""
212
```
213
214
#### Usage Examples
215
216
```python
217
from fastnumbers import try_forceint
218
219
# Truncation behavior
220
try_forceint('123.89') # 123 (truncated)
221
try_forceint(456.99) # 456 (truncated)
222
try_forceint('-78.12') # -78 (truncated)
223
224
# Compared to try_int
225
try_int('123.45') # '123.45' (can't convert)
226
try_forceint('123.45') # 123 (truncated)
227
228
# Error handling
229
try_forceint('invalid') # 'invalid' (INPUT default)
230
try_forceint('invalid', on_fail=0) # 0
231
try_forceint('invalid', on_fail=RAISE) # Raises ValueError
232
```
233
234
## Error Handling Strategies
235
236
All error-handling functions support multiple strategies for dealing with failures:
237
238
### on_fail Parameter Options
239
240
- **`INPUT`** (default): Return the original input unchanged
241
- **`RAISE`**: Raise ValueError with descriptive error message
242
- **Custom value**: Return any specified default value
243
- **Callable**: Call function with original input, return result
244
245
### on_type_error Parameter Options
246
247
- **`RAISE`** (default): Raise TypeError for invalid input types
248
- **`INPUT`**: Return the original input unchanged
249
- **Custom value**: Return any specified default value
250
- **Callable**: Call function with original input, return result
251
252
### Special Value Handling (inf/nan parameters)
253
254
- **`ALLOWED`** (default): Allow inf/nan values through unchanged
255
- **`INPUT`**: Return original string representation
256
- **`RAISE`**: Raise ValueError for inf/nan values
257
- **Custom value**: Replace inf/nan with specified value
258
- **Callable**: Transform inf/nan through custom function
259
260
## Type Safety
261
262
All functions use extensive type overloads to provide accurate return type information based on the parameters used, enabling proper static type checking and IDE support.