or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

commands-groups.mdcontext-management.mdexception-handling.mdformatting.mdindex.mdparameter-types.mdparameters.mdterminal-ui.mdtesting-support.md

parameter-types.mddocs/

0

# Parameter Types

1

2

Rich type system for validating and converting command-line inputs including built-in types for common patterns like file paths, choices, numeric ranges, and custom type creation.

3

4

## Capabilities

5

6

### Basic Parameter Types

7

8

Fundamental types for common data validation patterns.

9

10

```python { .api }

11

class ParamType:

12

name: str

13

is_composite: bool

14

envvar_list_splitter: str | None

15

16

def convert(self, value: str, param: Parameter | None, ctx: Context | None) -> Any:

17

"""

18

Convert string input to the appropriate type.

19

20

Parameters:

21

- value: Input string value

22

- param: Parameter being processed

23

- ctx: Current context

24

25

Returns:

26

Converted value

27

28

Raises:

29

BadParameter: If conversion fails

30

"""

31

32

def fail(self, message: str, param: Parameter | None = None, ctx: Context | None = None) -> NoReturn:

33

"""

34

Fail with a parameter error.

35

36

Parameters:

37

- message: Error message

38

- param: Parameter that failed

39

- ctx: Current context

40

"""

41

```

42

43

**Built-in Type Constants:**

44

45

```python { .api }

46

BOOL: BoolParamType # Boolean type (true/false, yes/no, 1/0)

47

INT: IntParamType # Integer type

48

FLOAT: FloatParamType # Float type

49

STRING: StringParamType # String type (default)

50

UUID: UUIDParameterType # UUID type

51

UNPROCESSED: UnprocessedParamType # Raw string type

52

```

53

54

### Choice Type

55

56

Restricts input to a predefined set of choices with optional case sensitivity.

57

58

```python { .api }

59

class Choice(ParamType):

60

choices: Iterable[str]

61

case_sensitive: bool

62

63

def __init__(self, choices: Iterable[str], case_sensitive: bool = True) -> None:

64

"""

65

Choice parameter type for restricted input values.

66

67

Parameters:

68

- choices: Allowed choice values

69

- case_sensitive: Whether matching is case sensitive

70

71

Usage:

72

@click.option('--format', type=click.Choice(['json', 'xml', 'yaml']))

73

@click.option('--level', type=click.Choice(['DEBUG', 'INFO', 'ERROR'], case_sensitive=False))

74

"""

75

```

76

77

### Numeric Range Types

78

79

Validates numeric input within specified ranges with optional clamping.

80

81

```python { .api }

82

class IntRange(IntParamType):

83

min: int | None

84

max: int | None

85

clamp: bool

86

87

def __init__(self, min: int | None = None, max: int | None = None, clamp: bool = False) -> None:

88

"""

89

Integer range parameter type.

90

91

Parameters:

92

- min: Minimum allowed value

93

- max: Maximum allowed value

94

- clamp: Clamp values to range instead of failing

95

96

Usage:

97

@click.option('--port', type=click.IntRange(1, 65535))

98

@click.option('--threads', type=click.IntRange(min=1, max=32, clamp=True))

99

"""

100

101

class FloatRange(FloatParamType):

102

min: float | None

103

max: float | None

104

clamp: bool

105

106

def __init__(self, min: float | None = None, max: float | None = None, clamp: bool = False) -> None:

107

"""

108

Float range parameter type.

109

110

Parameters:

111

- min: Minimum allowed value

112

- max: Maximum allowed value

113

- clamp: Clamp values to range instead of failing

114

115

Usage:

116

@click.option('--ratio', type=click.FloatRange(0.0, 1.0))

117

@click.option('--temperature', type=click.FloatRange(min=-273.15))

118

"""

119

```

120

121

### Path Type

122

123

Validates file and directory paths with existence checking and permission validation.

124

125

```python { .api }

126

class Path(ParamType):

127

exists: bool

128

file_okay: bool

129

dir_okay: bool

130

writable: bool

131

readable: bool

132

resolve_path: bool

133

allow_dash: bool

134

type: Type[str] | Type[bytes] | None

135

136

def __init__(

137

self,

138

exists: bool = False,

139

file_okay: bool = True,

140

dir_okay: bool = True,

141

writable: bool = False,

142

readable: bool = True,

143

resolve_path: bool = False,

144

allow_dash: bool = False,

145

path_type: Type[str] | Type[bytes] | None = None,

146

) -> None:

147

"""

148

Path parameter type for file system paths.

149

150

Parameters:

151

- exists: Path must exist

152

- file_okay: Accept file paths

153

- dir_okay: Accept directory paths

154

- writable: Path must be writable

155

- readable: Path must be readable

156

- resolve_path: Resolve to absolute path

157

- allow_dash: Allow '-' for stdin/stdout

158

- path_type: Return type (str or bytes)

159

160

Usage:

161

@click.option('--input', type=click.Path(exists=True, readable=True))

162

@click.option('--output', type=click.Path(writable=True))

163

@click.option('--config-dir', type=click.Path(exists=True, file_okay=False))

164

"""

165

166

def convert(self, value: str, param: Parameter | None, ctx: Context | None) -> str | bytes: ...

167

```

168

169

### File Type

170

171

Handles file opening with mode, encoding, and lazy loading options.

172

173

```python { .api }

174

class File(ParamType):

175

mode: str

176

encoding: str | None

177

errors: str | None

178

lazy: bool | None

179

atomic: bool

180

181

def __init__(

182

self,

183

mode: str = "r",

184

encoding: str | None = None,

185

errors: str | None = None,

186

lazy: bool | None = None,

187

atomic: bool = False,

188

) -> None:

189

"""

190

File parameter type for file objects.

191

192

Parameters:

193

- mode: File open mode ('r', 'w', 'rb', etc.)

194

- encoding: Text encoding

195

- errors: Error handling ('strict', 'ignore', 'replace')

196

- lazy: Lazy file opening

197

- atomic: Atomic file operations

198

199

Usage:

200

@click.option('--input', type=click.File('r'))

201

@click.option('--output', type=click.File('w', encoding='utf-8'))

202

@click.option('--data', type=click.File('rb'))

203

"""

204

205

def convert(self, value: str, param: Parameter | None, ctx: Context | None) -> IO[Any]: ...

206

```

207

208

### DateTime Type

209

210

Parses datetime strings with configurable formats.

211

212

```python { .api }

213

class DateTime(ParamType):

214

formats: Sequence[str]

215

216

def __init__(self, formats: Sequence[str] | None = None) -> None:

217

"""

218

DateTime parameter type for date/time parsing.

219

220

Parameters:

221

- formats: List of strptime format strings to try

222

223

Default formats:

224

- '%Y-%m-%d'

225

- '%Y-%m-%dT%H:%M:%S'

226

- '%Y-%m-%d %H:%M:%S'

227

228

Usage:

229

@click.option('--date', type=click.DateTime())

230

@click.option('--timestamp', type=click.DateTime(['%Y-%m-%d %H:%M:%S']))

231

"""

232

233

def convert(self, value: str, param: Parameter | None, ctx: Context | None) -> datetime.datetime: ...

234

```

235

236

### Tuple Type

237

238

Combines multiple parameter types into composite tuples.

239

240

```python { .api }

241

class Tuple(CompositeParamType):

242

types: list[ParamType]

243

arity: int

244

245

def __init__(self, types: Iterable[Any]) -> None:

246

"""

247

Tuple parameter type for composite values.

248

249

Parameters:

250

- types: List of types for tuple elements

251

252

Usage:

253

@click.option('--point', type=click.Tuple([int, int]))

254

@click.option('--coord', type=click.Tuple([float, float, str]))

255

"""

256

257

def convert(self, value: str, param: Parameter | None, ctx: Context | None) -> tuple: ...

258

```

259

260

### Advanced Types

261

262

Additional specialized parameter types.

263

264

```python { .api }

265

class UUIDParameterType(ParamType):

266

def convert(self, value: str, param: Parameter | None, ctx: Context | None) -> uuid.UUID:

267

"""

268

UUID parameter type.

269

270

Usage:

271

@click.option('--id', type=click.UUID)

272

"""

273

274

class UnprocessedParamType(ParamType):

275

"""

276

Unprocessed parameter type that passes values through unchanged.

277

278

Usage:

279

@click.option('--raw', type=click.UNPROCESSED)

280

"""

281

282

class FuncParamType(ParamType):

283

func: Callable[[str | None], Any]

284

285

def __init__(self, func: Callable[[str | None], Any]) -> None:

286

"""

287

Function-based parameter type for custom conversion.

288

289

Parameters:

290

- func: Conversion function

291

292

Usage:

293

def parse_coordinates(value):

294

if value is None:

295

return None

296

try:

297

x, y = value.split(',')

298

return (float(x), float(y))

299

except ValueError:

300

raise click.BadParameter('Coordinates must be in format "x,y"')

301

302

@click.option('--coords', type=click.FuncParamType(parse_coordinates))

303

"""

304

305

def convert(self, value: str, param: Parameter | None, ctx: Context | None) -> Any: ...

306

```

307

308

### Type Conversion Utilities

309

310

Helper functions for working with parameter types.

311

312

```python { .api }

313

def convert_type(ty: Any | None, default: Any | None = None) -> ParamType:

314

"""

315

Convert various type specifications to ParamType instances.

316

317

Parameters:

318

- ty: Type specification (type, ParamType, tuple, callable)

319

- default: Default value for type inference

320

321

Returns:

322

ParamType instance

323

324

Usage:

325

# These are equivalent:

326

click.option('--count', type=int)

327

click.option('--count', type=click.INT)

328

click.option('--count', type=click.convert_type(int))

329

"""

330

```

331

332

### Custom Parameter Types

333

334

Base classes for creating custom parameter types.

335

336

```python { .api }

337

class CompositeParamType(ParamType):

338

arity: int

339

"""

340

Base class for parameter types that consume multiple arguments.

341

"""

342

343

class BoolParamType(ParamType):

344

"""

345

Boolean parameter type accepting various true/false representations.

346

347

Accepts: true/false, yes/no, 1/0, on/off (case insensitive)

348

"""

349

350

class StringParamType(ParamType):

351

"""

352

String parameter type (default for all parameters).

353

"""

354

355

class IntParamType(ParamType):

356

"""

357

Integer parameter type with validation.

358

"""

359

360

class FloatParamType(ParamType):

361

"""

362

Float parameter type with validation.

363

"""

364

```

365

366

**Custom Type Example:**

367

368

```python

369

class EmailType(click.ParamType):

370

name = 'email'

371

372

def convert(self, value, param, ctx):

373

if value is None:

374

return None

375

376

if '@' not in value:

377

self.fail(f'{value} is not a valid email address', param, ctx)

378

379

return value.lower()

380

381

# Usage

382

@click.option('--email', type=EmailType())

383

def register(email):

384

click.echo(f'Registering {email}')

385

```

386

387

## Type Constants

388

389

Pre-defined type instances for common parameter types, providing convenient shortcuts.

390

391

```python { .api }

392

BOOL: BoolParamType

393

"""Boolean parameter type constant."""

394

395

FLOAT: FloatParamType

396

"""Float parameter type constant."""

397

398

INT: IntParamType

399

"""Integer parameter type constant."""

400

401

STRING: StringParamType

402

"""String parameter type constant."""

403

404

UNPROCESSED: UnprocessedParamType

405

"""Unprocessed parameter type constant (passes value as-is)."""

406

407

UUID: UUIDParameterType

408

"""UUID parameter type constant."""

409

```

410

411

**Usage with Type Constants:**

412

413

```python

414

# Using type constants instead of classes

415

@click.option('--count', type=click.INT)

416

@click.option('--ratio', type=click.FLOAT)

417

@click.option('--enabled', type=click.BOOL)

418

@click.option('--user-id', type=click.UUID)

419

def process(count, ratio, enabled, user_id):

420

click.echo(f"Count: {count} ({type(count)})")

421

click.echo(f"Ratio: {ratio} ({type(ratio)})")

422

click.echo(f"Enabled: {enabled} ({type(enabled)})")

423

click.echo(f"User ID: {user_id} ({type(user_id)})")

424

425

# Equivalent to:

426

@click.option('--count', type=int)

427

@click.option('--ratio', type=float)

428

@click.option('--enabled', type=bool)

429

@click.option('--user-id', type=click.types.UUIDParameterType())

430

def process_equivalent(count, ratio, enabled, user_id):

431

# Same functionality

432

pass

433

```