or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

builtin-replacements.mdchecking.mderror-handling.mdhigh-performance.mdindex.mdutilities.md

builtin-replacements.mddocs/

0

# Built-in Replacements

1

2

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.

3

4

## Capabilities

5

6

### Integer Replacement

7

8

High-performance drop-in replacement for Python's built-in `int()` function with identical behavior and API.

9

10

```python { .api }

11

def int(x=0, base=10):

12

"""

13

Drop-in replacement for Python's built-in int() function.

14

15

Parameters:

16

- x: Value to convert to integer (default: 0)

17

- base: Number base for string conversion (default: 10)

18

19

Returns:

20

- int: Integer representation of input

21

22

Raises:

23

- ValueError: If string cannot be converted to int

24

- TypeError: If input type is invalid

25

"""

26

```

27

28

#### Usage Examples

29

30

```python

31

from fastnumbers import int

32

33

# Direct replacement usage

34

int() # 0 (default)

35

int(42) # 42

36

int(3.14) # 3 (truncated)

37

int('123') # 123

38

int(' 456 ') # 456 (whitespace handled)

39

40

# Base conversion (identical to built-in)

41

int('ff', 16) # 255 (hexadecimal)

42

int('1010', 2) # 10 (binary)

43

int('777', 8) # 511 (octal)

44

45

# Error behavior (identical to built-in)

46

int('123.45') # ValueError: invalid literal for int()

47

int('invalid') # ValueError: invalid literal for int()

48

int([1, 2, 3]) # TypeError: int() argument must be a string...

49

50

# Special cases (identical to built-in)

51

int(True) # 1

52

int(False) # 0

53

int(-3.99) # -3 (truncated toward zero)

54

```

55

56

### Float Replacement

57

58

High-performance drop-in replacement for Python's built-in `float()` function with identical behavior and API.

59

60

```python { .api }

61

def float(x=0.0):

62

"""

63

Drop-in replacement for Python's built-in float() function.

64

65

Parameters:

66

- x: Value to convert to float (default: 0.0)

67

68

Returns:

69

- float: Float representation of input

70

71

Raises:

72

- ValueError: If string cannot be converted to float

73

- TypeError: If input type is invalid

74

"""

75

```

76

77

#### Usage Examples

78

79

```python

80

from fastnumbers import float

81

82

# Direct replacement usage

83

float() # 0.0 (default)

84

float(42) # 42.0

85

float('123.45') # 123.45

86

float(' -67.89 ') # -67.89 (whitespace handled)

87

88

# Scientific notation (identical to built-in)

89

float('1e5') # 100000.0

90

float('1.23e-4') # 0.000123

91

float('-2.5E+2') # -250.0

92

93

# Special values (identical to built-in)

94

float('inf') # inf

95

float('-inf') # -inf

96

float('nan') # nan

97

float('infinity') # inf

98

float('-infinity') # -inf

99

100

# Error behavior (identical to built-in)

101

float('invalid') # ValueError: could not convert string to float

102

float([1, 2, 3]) # TypeError: float() argument must be a string...

103

104

# Type conversion (identical to built-in)

105

float(True) # 1.0

106

float(False) # 0.0

107

```

108

109

### Real Number Function

110

111

Extended function that converts to the most appropriate numeric type (int or float) based on the value, with optional coercion control.

112

113

```python { .api }

114

def real(x=0.0, *, coerce=True):

115

"""

116

Convert to the most appropriate numeric type (int or float).

117

118

Parameters:

119

- x: Value to convert (default: 0.0)

120

- coerce: Whether to coerce floats to ints when possible (default: True)

121

122

Returns:

123

- Union[int, float]: Most appropriate numeric representation

124

125

Raises:

126

- ValueError: If string cannot be converted to number

127

- TypeError: If input type is invalid

128

"""

129

```

130

131

#### Usage Examples

132

133

```python

134

from fastnumbers import real

135

136

# Automatic type selection

137

real('123') # 123 (int)

138

real('123.0') # 123 (int, coerced)

139

real('123.45') # 123.45 (float)

140

real(456.0) # 456 (int, coerced)

141

real(456.7) # 456.7 (float)

142

143

# Coercion control

144

real('123.0', coerce=True) # 123 (int)

145

real('123.0', coerce=False) # 123.0 (float)

146

real(456.0, coerce=True) # 456 (int)

147

real(456.0, coerce=False) # 456.0 (float)

148

149

# Default behavior

150

real() # 0 (int, since 0.0 coerces to 0)

151

real(coerce=False) # 0.0 (float)

152

153

# Complex cases

154

real('1e2') # 100 (int, since 100.0 coerces)

155

real('1e-1', coerce=False) # 0.1 (float)

156

157

# Error behavior (like built-ins)

158

real('invalid') # ValueError: could not convert string to real

159

```

160

161

## Performance Comparisons

162

163

These replacement functions provide significant performance improvements over Python's built-ins:

164

165

| Function | Speedup vs Built-in | Use Case |

166

|----------|-------------------|-----------|

167

| `fastnumbers.int()` | 2-10x faster | String to int conversion |

168

| `fastnumbers.float()` | 2-15x faster | String to float conversion |

169

| `fastnumbers.real()` | 2-12x faster | Optimal type conversion |

170

171

### Benchmarking Examples

172

173

```python

174

import timeit

175

from fastnumbers import int as fast_int, float as fast_float

176

177

# Integer conversion performance

178

builtin_time = timeit.timeit(lambda: int('12345'), number=100000)

179

fast_time = timeit.timeit(lambda: fast_int('12345'), number=100000)

180

print(f"Integer speedup: {builtin_time / fast_time:.1f}x")

181

182

# Float conversion performance

183

builtin_time = timeit.timeit(lambda: float('123.45'), number=100000)

184

fast_time = timeit.timeit(lambda: fast_float('123.45'), number=100000)

185

print(f"Float speedup: {builtin_time / fast_time:.1f}x")

186

```

187

188

## Compatibility Notes

189

190

### Complete Drop-in Compatibility

191

192

These functions are designed to be complete drop-in replacements:

193

194

```python

195

# Can replace built-ins directly

196

import fastnumbers

197

import builtins

198

199

# Shadow built-ins (use with caution)

200

int = fastnumbers.int

201

float = fastnumbers.float

202

203

# Or use module-level replacement

204

import fastnumbers as fn

205

result = fn.int('123')

206

```

207

208

### Identical Error Behavior

209

210

Error messages and exception types match Python's built-ins exactly:

211

212

```python

213

# Both raise identical ValueErrors

214

try:

215

int('invalid')

216

except ValueError as e:

217

print(e) # "invalid literal for int() with base 10: 'invalid'"

218

219

try:

220

fastnumbers.int('invalid')

221

except ValueError as e:

222

print(e) # "invalid literal for int() with base 10: 'invalid'"

223

```

224

225

### Edge Case Handling

226

227

All edge cases are handled identically to built-ins:

228

229

```python

230

# Whitespace handling

231

int(' 123 ') == fastnumbers.int(' 123 ') # True

232

233

# Special float values

234

float('inf') == fastnumbers.float('inf') # True

235

float('nan') != fastnumbers.float('nan') # True (NaN != NaN)

236

237

# Type coercion

238

int(True) == fastnumbers.int(True) # True (1)

239

float(False) == fastnumbers.float(False) # True (0.0)

240

```

241

242

## Integration Patterns

243

244

### Selective Replacement

245

246

Replace only performance-critical conversions:

247

248

```python

249

from fastnumbers import int as fast_int, float as fast_float

250

251

def process_data(raw_values):

252

# Use fast versions for bulk processing

253

return [fast_float(x) for x in raw_values if fast_int(x, 0) > 0]

254

```

255

256

### Module-Level Import

257

258

Import entire module for consistent performance:

259

260

```python

261

import fastnumbers as fn

262

263

# Use fn.int, fn.float throughout codebase

264

def parse_config(config_dict):

265

return {

266

'port': fn.int(config_dict.get('port', '8080')),

267

'timeout': fn.float(config_dict.get('timeout', '30.0')),

268

'max_size': fn.real(config_dict.get('max_size', '1000'))

269

}

270

```

271

272

### Performance-Critical Sections

273

274

Use in tight loops and data processing:

275

276

```python

277

from fastnumbers import int as fast_int, real as fast_real

278

279

def process_csv_row(row):

280

# Fast conversion in data processing pipeline

281

return [fast_real(cell) for cell in row if cell.strip()]

282

283

def parse_large_dataset(lines):

284

# Bulk processing with performance replacements

285

return [process_csv_row(line.split(',')) for line in lines]

286

```

287

288

These functions provide the easiest path to performance improvements in existing codebases that heavily use built-in number conversion functions.