or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

color-constants.mdcore-application.mdfile-handling.mdindex.mdparameter-configuration.mdterminal-utilities.mdtesting-support.md

parameter-configuration.mddocs/

0

# Parameter Configuration

1

2

Functions for configuring command-line arguments and options in Typer applications, providing type validation, help text, prompting, and advanced input handling.

3

4

## Capabilities

5

6

### Option Configuration

7

8

Configure command-line options (flags starting with -- or -) with extensive customization options.

9

10

```python { .api }

11

def Option(

12

default: Optional[Any] = ...,

13

*param_decls: str,

14

callback: Optional[Callable[..., Any]] = None,

15

metavar: Optional[str] = None,

16

expose_value: bool = True,

17

is_eager: bool = False,

18

envvar: Optional[Union[str, List[str]]] = None,

19

shell_complete: Optional[Callable] = None,

20

autocompletion: Optional[Callable[..., Any]] = None,

21

default_factory: Optional[Callable[[], Any]] = None,

22

parser: Optional[Callable[[str], Any]] = None,

23

click_type: Optional[click.ParamType] = None,

24

show_default: Union[bool, str] = True,

25

prompt: Union[bool, str] = False,

26

confirmation_prompt: bool = False,

27

prompt_required: bool = True,

28

hide_input: bool = False,

29

count: bool = False,

30

allow_from_autoenv: bool = True,

31

help: Optional[str] = None,

32

hidden: bool = False,

33

show_choices: bool = True,

34

show_envvar: bool = True,

35

case_sensitive: bool = True,

36

min: Optional[Union[int, float]] = None,

37

max: Optional[Union[int, float]] = None,

38

clamp: bool = False,

39

formats: Optional[List[str]] = None,

40

mode: Optional[str] = None,

41

encoding: Optional[str] = None,

42

errors: Optional[str] = "strict",

43

lazy: Optional[bool] = None,

44

atomic: bool = False,

45

exists: bool = False,

46

file_okay: bool = True,

47

dir_okay: bool = True,

48

writable: bool = False,

49

readable: bool = True,

50

resolve_path: bool = False,

51

allow_dash: bool = False,

52

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

53

rich_help_panel: Union[str, None] = None,

54

) -> Any:

55

"""

56

Define a command-line option.

57

58

Parameters:

59

- default: Default value for the option

60

- param_decls: Alternative names for the option (e.g., "-v", "--verbose")

61

- callback: Function called when option is parsed

62

- metavar: Name shown in help for the option's value

63

- expose_value: Whether to pass the option value to the command function

64

- is_eager: Process this option before others

65

- envvar: Environment variable name(s) to read default from

66

- shell_complete: Shell completion function

67

- autocompletion: Auto-completion function

68

- default_factory: Function to generate default value

69

- parser: Custom parsing function

70

- click_type: Custom Click parameter type

71

- show_default: Show default value in help

72

- prompt: Prompt user for value if not provided

73

- confirmation_prompt: Ask for confirmation when prompting

74

- prompt_required: Require value when prompting

75

- hide_input: Hide input when prompting (for passwords)

76

- count: Count number of times option is used

77

- allow_from_autoenv: Allow reading from environment

78

- help: Help text for the option

79

- hidden: Hide option from help

80

- show_choices: Show available choices in help

81

- show_envvar: Show environment variable in help

82

- case_sensitive: Case sensitive choice matching

83

- min/max: Numeric range validation

84

- clamp: Clamp numeric values to range

85

- formats: DateTime format strings

86

- mode: File open mode

87

- encoding: File encoding

88

- errors: Error handling for file operations

89

- lazy: Lazy file opening

90

- atomic: Atomic file operations

91

- exists: Path must exist

92

- file_okay: Allow files

93

- dir_okay: Allow directories

94

- writable: Path must be writable

95

- readable: Path must be readable

96

- resolve_path: Resolve path to absolute

97

- allow_dash: Allow dash as stdin/stdout

98

- path_type: Path string type

99

- rich_help_panel: Rich formatting help panel

100

101

Returns:

102

OptionInfo instance for use as parameter annotation

103

"""

104

```

105

106

### Argument Configuration

107

108

Configure positional command-line arguments with validation and help text.

109

110

```python { .api }

111

def Argument(

112

default: Optional[Any] = ...,

113

*,

114

callback: Optional[Callable[..., Any]] = None,

115

metavar: Optional[str] = None,

116

expose_value: bool = True,

117

is_eager: bool = False,

118

envvar: Optional[Union[str, List[str]]] = None,

119

shell_complete: Optional[Callable] = None,

120

autocompletion: Optional[Callable[..., Any]] = None,

121

default_factory: Optional[Callable[[], Any]] = None,

122

parser: Optional[Callable[[str], Any]] = None,

123

click_type: Optional[click.ParamType] = None,

124

show_default: Union[bool, str] = True,

125

show_choices: bool = True,

126

show_envvar: bool = True,

127

help: Optional[str] = None,

128

hidden: bool = False,

129

case_sensitive: bool = True,

130

min: Optional[Union[int, float]] = None,

131

max: Optional[Union[int, float]] = None,

132

clamp: bool = False,

133

formats: Optional[List[str]] = None,

134

mode: Optional[str] = None,

135

encoding: Optional[str] = None,

136

errors: Optional[str] = "strict",

137

lazy: Optional[bool] = None,

138

atomic: bool = False,

139

exists: bool = False,

140

file_okay: bool = True,

141

dir_okay: bool = True,

142

writable: bool = False,

143

readable: bool = True,

144

resolve_path: bool = False,

145

allow_dash: bool = False,

146

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

147

rich_help_panel: Union[str, None] = None,

148

) -> Any:

149

"""

150

Define a command-line argument.

151

152

Parameters:

153

Similar to Option but for positional arguments. Arguments cannot have

154

param_decls, prompt, confirmation_prompt, prompt_required, hide_input,

155

count, or allow_from_autoenv parameters.

156

157

Returns:

158

ArgumentInfo instance for use as parameter annotation

159

"""

160

```

161

162

## Usage Examples

163

164

### Basic Options and Arguments

165

166

```python

167

import typer

168

from typing import Optional

169

170

def main(

171

name: str = typer.Argument(..., help="Name of the person to greet"),

172

count: int = typer.Option(1, "--count", "-c", help="Number of greetings"),

173

polite: bool = typer.Option(False, "--polite", help="Use polite greeting"),

174

greeting: Optional[str] = typer.Option(None, help="Custom greeting message")

175

):

176

"""Greet someone with customizable options."""

177

message = greeting or ("Good day" if polite else "Hello")

178

for i in range(count):

179

typer.echo(f"{message} {name}!")

180

181

if __name__ == "__main__":

182

typer.run(main)

183

```

184

185

### Prompting for Input

186

187

```python

188

import typer

189

190

def create_user(

191

username: str = typer.Option(..., prompt=True, help="Username for the new user"),

192

password: str = typer.Option(..., prompt=True, hide_input=True, confirmation_prompt=True, help="Password for the user"),

193

email: str = typer.Option(..., prompt="Email address", help="Email for the user")

194

):

195

"""Create a new user with prompted input."""

196

typer.echo(f"Creating user {username} with email {email}")

197

198

if __name__ == "__main__":

199

typer.run(create_user)

200

```

201

202

### File Parameters

203

204

```python

205

import typer

206

from pathlib import Path

207

208

def process_file(

209

input_file: Path = typer.Argument(..., exists=True, file_okay=True, dir_okay=False, help="Input file to process"),

210

output_file: Path = typer.Option("output.txt", "--output", "-o", writable=True, help="Output file path"),

211

config: Path = typer.Option(None, exists=True, dir_okay=False, help="Configuration file")

212

):

213

"""Process a file with optional configuration."""

214

typer.echo(f"Processing {input_file} -> {output_file}")

215

if config:

216

typer.echo(f"Using config: {config}")

217

218

if __name__ == "__main__":

219

typer.run(process_file)

220

```

221

222

### Numeric Ranges and Validation

223

224

```python

225

import typer

226

227

def set_volume(

228

level: int = typer.Option(..., min=0, max=100, clamp=True, help="Volume level (0-100)"),

229

precision: float = typer.Option(1.0, min=0.1, max=10.0, help="Precision factor")

230

):

231

"""Set volume with validation."""

232

typer.echo(f"Setting volume to {level} with precision {precision}")

233

234

if __name__ == "__main__":

235

typer.run(set_volume)

236

```

237

238

### Environment Variables

239

240

```python

241

import typer

242

from typing import Optional

243

244

def connect(

245

host: str = typer.Option("localhost", envvar="DB_HOST", help="Database host"),

246

port: int = typer.Option(5432, envvar="DB_PORT", help="Database port"),

247

username: str = typer.Option(..., envvar="DB_USER", help="Database username"),

248

password: Optional[str] = typer.Option(None, envvar="DB_PASSWORD", hide_input=True, help="Database password")

249

):

250

"""Connect to database using environment variables."""

251

if password is None:

252

password = typer.prompt("Password", hide_input=True)

253

typer.echo(f"Connecting to {host}:{port} as {username}")

254

255

if __name__ == "__main__":

256

typer.run(connect)

257

```

258

259

### Choices and Enums

260

261

```python

262

import typer

263

from enum import Enum

264

265

class LogLevel(str, Enum):

266

DEBUG = "debug"

267

INFO = "info"

268

WARNING = "warning"

269

ERROR = "error"

270

271

def log_message(

272

message: str = typer.Argument(..., help="Message to log"),

273

level: LogLevel = typer.Option(LogLevel.INFO, help="Log level"),

274

format_type: str = typer.Option("text", click_type=typer.Choice(["text", "json", "xml"]), help="Output format")

275

):

276

"""Log a message with specified level and format."""

277

typer.echo(f"[{level.value.upper()}] {message} (format: {format_type})")

278

279

if __name__ == "__main__":

280

typer.run(log_message)

281

```

282

283

### Multiple Values

284

285

```python

286

import typer

287

from typing import List, Optional

288

289

def process_items(

290

items: List[str] = typer.Argument(..., help="Items to process"),

291

tags: Optional[List[str]] = typer.Option(None, "--tag", help="Tags to apply"),

292

exclude: Optional[List[str]] = typer.Option(None, "--exclude", help="Items to exclude")

293

):

294

"""Process multiple items with optional tags and exclusions."""

295

typer.echo(f"Processing items: {', '.join(items)}")

296

if tags:

297

typer.echo(f"Tags: {', '.join(tags)}")

298

if exclude:

299

typer.echo(f"Excluding: {', '.join(exclude)}")

300

301

if __name__ == "__main__":

302

typer.run(process_items)

303

```

304

305

### Custom Validation

306

307

```python

308

import typer

309

from typing import Optional

310

311

def validate_email(value: str) -> str:

312

"""Simple email validation."""

313

if "@" not in value:

314

raise typer.BadParameter("Email must contain @ symbol")

315

return value

316

317

def send_email(

318

to: str = typer.Option(..., parser=validate_email, help="Recipient email address"),

319

subject: str = typer.Option("", help="Email subject"),

320

body: Optional[str] = typer.Option(None, help="Email body")

321

):

322

"""Send an email with validation."""

323

typer.echo(f"Sending email to {to}")

324

typer.echo(f"Subject: {subject}")

325

if body:

326

typer.echo(f"Body: {body}")

327

328

if __name__ == "__main__":

329

typer.run(send_email)

330

```