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

utilities.mddocs/

0

# Utility Functions

1

2

Additional utility functions for type analysis and deprecated functions maintained for backward compatibility. These functions provide specialized capabilities for introspecting numeric types and supporting legacy code.

3

4

## Capabilities

5

6

### Type Query Function

7

8

Analyzes input to determine what numeric type it represents without performing conversion, useful for type introspection and conditional processing.

9

10

```python { .api }

11

def query_type(

12

x,

13

*,

14

allow_inf=False,

15

allow_nan=False,

16

coerce=False,

17

allowed_types=None,

18

allow_underscores=False

19

):

20

"""

21

Determine the numeric type of input without conversion.

22

23

Parameters:

24

- x: Input to analyze (any type)

25

- allow_inf: Allow infinity values (default: False)

26

- allow_nan: Allow NaN values (default: False)

27

- coerce: Enable type coercion analysis (default: False)

28

- allowed_types: Sequence of allowed types to check against (optional)

29

- allow_underscores: Allow underscores in numeric strings (default: False)

30

31

Returns:

32

- Type[int] | Type[float] | Type[input] | None: Detected numeric type or None

33

"""

34

```

35

36

#### Usage Examples

37

38

```python

39

from fastnumbers import query_type

40

41

# Basic type detection

42

query_type('123') # <class 'int'>

43

query_type('123.45') # <class 'float'>

44

query_type(456) # <class 'int'>

45

query_type(78.9) # <class 'float'>

46

query_type('invalid') # <class 'str'> (original type)

47

48

# Coercion analysis

49

query_type('123.0') # <class 'str'> (no coercion)

50

query_type('123.0', coerce=True) # <class 'int'> (would coerce to int)

51

query_type(456.0) # <class 'float'>

52

query_type(456.0, coerce=True) # <class 'int'> (would coerce to int)

53

54

# Special value handling

55

query_type('inf') # <class 'str'> (inf not allowed)

56

query_type('inf', allow_inf=True) # <class 'float'> (inf allowed)

57

query_type('nan', allow_nan=True) # <class 'float'> (nan allowed)

58

59

# Type filtering

60

allowed = [int, float]

61

query_type('123', allowed_types=allowed) # <class 'int'>

62

query_type('invalid', allowed_types=allowed) # None (not in allowed types)

63

64

# Formatting support

65

query_type('1_000', allow_underscores=True) # <class 'int'>

66

query_type('1_000') # <class 'str'> (underscores not allowed)

67

```

68

69

#### Advanced Type Analysis

70

71

```python

72

# Conditional processing based on type

73

def smart_convert(value):

74

detected_type = query_type(value, coerce=True, allow_inf=True, allow_nan=True)

75

76

if detected_type == int:

77

return int(value)

78

elif detected_type == float:

79

return float(value)

80

else:

81

return value # Keep as original type

82

83

# Type validation in data pipelines

84

def validate_numeric_column(values, expected_type):

85

"""Validate that all values can be converted to expected type."""

86

allowed_types = [expected_type]

87

88

for i, value in enumerate(values):

89

if query_type(value, allowed_types=allowed_types) is None:

90

raise ValueError(f"Value at index {i} cannot be converted to {expected_type.__name__}: {value}")

91

92

return True

93

94

# Schema inference

95

def infer_column_type(values):

96

"""Infer the best numeric type for a column of data."""

97

type_counts = {'int': 0, 'float': 0, 'other': 0}

98

99

for value in values:

100

detected = query_type(value, coerce=True, allow_inf=True, allow_nan=True)

101

if detected == int:

102

type_counts['int'] += 1

103

elif detected == float:

104

type_counts['float'] += 1

105

else:

106

type_counts['other'] += 1

107

108

if type_counts['other'] > 0:

109

return str # Mixed types, keep as string

110

elif type_counts['float'] > 0:

111

return float # Any floats mean float column

112

else:

113

return int # All integers

114

```

115

116

## Deprecated Functions

117

118

These functions are maintained for backward compatibility but are deprecated in favor of their `check_*` equivalents. They provide the same functionality with slightly different parameter names and defaults.

119

120

### Deprecated Real Checking

121

122

```python { .api }

123

def isreal(

124

x,

125

*,

126

str_only=False,

127

num_only=False,

128

allow_inf=False,

129

allow_nan=False,

130

allow_underscores=True

131

) -> bool:

132

"""

133

DEPRECATED: Use check_real() instead.

134

135

Check if input represents a real number.

136

"""

137

```

138

139

### Deprecated Float Checking

140

141

```python { .api }

142

def isfloat(

143

x,

144

*,

145

str_only=False,

146

num_only=False,

147

allow_inf=False,

148

allow_nan=False,

149

allow_underscores=True

150

) -> bool:

151

"""

152

DEPRECATED: Use check_float() instead.

153

154

Check if input represents a float.

155

"""

156

```

157

158

### Deprecated Integer Checking

159

160

```python { .api }

161

def isint(

162

x,

163

*,

164

str_only=False,

165

num_only=False,

166

base=0,

167

allow_underscores=True

168

) -> bool:

169

"""

170

DEPRECATED: Use check_int() instead.

171

172

Check if input represents an integer.

173

"""

174

```

175

176

### Deprecated Integer-like Checking

177

178

```python { .api }

179

def isintlike(

180

x,

181

*,

182

str_only=False,

183

num_only=False,

184

allow_underscores=True

185

) -> bool:

186

"""

187

DEPRECATED: Use check_intlike() instead.

188

189

Check if input represents an integer-like value.

190

"""

191

```

192

193

#### Migration Guide

194

195

```python

196

# OLD (deprecated)

197

from fastnumbers import isreal, isfloat, isint, isintlike

198

199

isreal('123', str_only=True) # DEPRECATED

200

isfloat('123.45', num_only=True) # DEPRECATED

201

isint('123', str_only=True) # DEPRECATED

202

isintlike('123.0') # DEPRECATED

203

204

# NEW (recommended)

205

from fastnumbers import check_real, check_float, check_int, check_intlike

206

from fastnumbers import STRING_ONLY, NUMBER_ONLY

207

208

check_real('123', consider=STRING_ONLY) # RECOMMENDED

209

check_float('123.45', consider=NUMBER_ONLY) # RECOMMENDED

210

check_int('123', consider=STRING_ONLY) # RECOMMENDED

211

check_intlike('123.0') # RECOMMENDED

212

```

213

214

## Version Information

215

216

Access to the package version for compatibility checking and logging.

217

218

```python { .api }

219

__version__: str # Package version string (e.g., "4.0.1")

220

```

221

222

#### Usage Examples

223

224

```python

225

import fastnumbers

226

227

# Version checking

228

print(f"Using fastnumbers version: {fastnumbers.__version__}")

229

230

# Compatibility checking

231

def check_fastnumbers_version(min_version):

232

"""Check if fastnumbers version meets minimum requirement."""

233

from packaging import version

234

current = version.parse(fastnumbers.__version__)

235

required = version.parse(min_version)

236

return current >= required

237

238

# Feature availability

239

def has_underscore_support():

240

"""Check if version supports underscore parameter."""

241

return check_fastnumbers_version("2.0.0")

242

243

# Logging setup

244

import logging

245

logging.info(f"Initialized fastnumbers {fastnumbers.__version__}")

246

```

247

248

## Utility Patterns

249

250

### Type-Aware Processing

251

252

```python

253

def process_mixed_data(values):

254

"""Process mixed numeric/string data intelligently."""

255

results = []

256

257

for value in values:

258

value_type = query_type(value, coerce=True, allow_inf=True, allow_nan=True)

259

260

if value_type == int:

261

results.append(('integer', int(value)))

262

elif value_type == float:

263

results.append(('float', float(value)))

264

else:

265

results.append(('string', str(value)))

266

267

return results

268

```

269

270

### Data Validation Pipeline

271

272

```python

273

def validate_and_convert(data, target_type):

274

"""Validate data can be converted before attempting conversion."""

275

# Pre-validate all data

276

allowed_types = [target_type]

277

invalid_indices = []

278

279

for i, value in enumerate(data):

280

if query_type(value, allowed_types=allowed_types) is None:

281

invalid_indices.append(i)

282

283

if invalid_indices:

284

raise ValueError(f"Invalid values at indices: {invalid_indices}")

285

286

# Convert validated data

287

if target_type == int:

288

return [int(x) for x in data]

289

elif target_type == float:

290

return [float(x) for x in data]

291

else:

292

return data

293

```

294

295

### Schema Evolution

296

297

```python

298

def evolve_schema(old_data, new_requirements):

299

"""Evolve data schema based on new type requirements."""

300

evolved_data = []

301

302

for value in old_data:

303

# Analyze current type

304

current_type = query_type(value, coerce=True)

305

306

# Convert based on new requirements

307

if new_requirements == 'strict_int' and current_type != int:

308

raise ValueError(f"Cannot convert {value} to strict int")

309

elif new_requirements == 'numeric' and current_type in [int, float]:

310

evolved_data.append(float(value) if current_type == int else value)

311

else:

312

evolved_data.append(value)

313

314

return evolved_data

315

```

316

317

These utility functions enable sophisticated numeric type analysis and provide pathways for migrating legacy code to the modern fastnumbers API.