0
# Parameters
1
2
Decorators and classes for defining command-line options and arguments with rich type validation, default values, prompts, and help text. Parameters provide the interface between users and command functionality.
3
4
## Capabilities
5
6
### Option Definition
7
8
Creates command-line options (flags and named parameters) with extensive configuration options for validation, prompting, and user interaction.
9
10
```python { .api }
11
def option(
12
*param_decls: str,
13
cls: Type[Option] = Option,
14
show_default: bool | str = False,
15
prompt: bool | str = False,
16
confirmation_prompt: bool = False,
17
hide_input: bool = False,
18
is_flag: bool | None = None,
19
flag_value: Any | None = None,
20
multiple: bool = False,
21
count: bool = False,
22
allow_from_autoenv: bool = True,
23
type: _ConvertibleType | None = None,
24
help: str | None = None,
25
show_choices: bool = True,
26
show_envvar: bool = False,
27
hidden: bool = False,
28
autocompletion: Callable[[Context, list[str], str], Iterable[str | tuple[str, str]]] | None = None,
29
default: Any | None = None,
30
required: bool = False,
31
callback: _Callback | None = None,
32
nargs: int | None = None,
33
metavar: str | None = None,
34
expose_value: bool = True,
35
is_eager: bool = False,
36
envvar: str | list[str] | None = None,
37
**kwargs: Any,
38
) -> IdentityFunction:
39
"""
40
Decorator that adds an option to a command.
41
42
Parameters:
43
- param_decls: Option declarations (e.g., '--verbose', '-v')
44
- cls: Option class to use
45
- show_default: Show default value in help
46
- prompt: Prompt for value if not provided
47
- confirmation_prompt: Require confirmation for sensitive input
48
- hide_input: Hide input (for passwords)
49
- is_flag: Whether this is a boolean flag
50
- flag_value: Value when flag is present
51
- multiple: Allow multiple values
52
- count: Count occurrences of flag
53
- allow_from_autoenv: Allow value from environment
54
- type: Parameter type for validation
55
- help: Help text
56
- show_choices: Show choices in help for Choice type
57
- show_envvar: Show environment variable name in help
58
- hidden: Hide option from help output
59
- autocompletion: Function for shell autocompletion
60
- default: Default value
61
- required: Whether parameter is required
62
- callback: Validation/transformation callback
63
- nargs: Number of arguments
64
- metavar: Placeholder for help text
65
- expose_value: Whether to pass value to function
66
- is_eager: Process before other parameters
67
- envvar: Environment variable name(s)
68
69
Returns:
70
Option decorator function
71
"""
72
```
73
74
**Usage Examples:**
75
76
```python
77
# Basic flag
78
@click.option('--verbose', is_flag=True, help='Enable verbose output')
79
80
# Option with default value
81
@click.option('--count', default=1, help='Number of iterations')
82
83
# Required option
84
@click.option('--name', required=True, help='Your name')
85
86
# Option with prompt
87
@click.option('--password', prompt=True, hide_input=True)
88
89
# Option with choices
90
@click.option('--format', type=click.Choice(['json', 'xml', 'yaml']))
91
92
# Multiple values
93
@click.option('--tag', multiple=True, help='Tags to apply')
94
95
# Environment variable support
96
@click.option('--debug', envvar='DEBUG', is_flag=True)
97
```
98
99
### Argument Definition
100
101
Creates positional command-line arguments with validation and type conversion.
102
103
```python { .api }
104
def argument(
105
*param_decls: str,
106
cls: Type[Argument] = Argument,
107
required: bool | None = None,
108
type: _ConvertibleType | None = None,
109
default: Any | None = None,
110
callback: _Callback | None = None,
111
nargs: int | None = None,
112
metavar: str | None = None,
113
expose_value: bool = True,
114
is_eager: bool = False,
115
envvar: str | list[str] | None = None,
116
autocompletion: Callable[[Context, list[str], str], Iterable[str | tuple[str, str]]] | None = None,
117
) -> IdentityFunction:
118
"""
119
Decorator that adds an argument to a command.
120
121
Parameters:
122
- param_decls: Argument declarations
123
- cls: Argument class to use
124
- required: Whether argument is required
125
- type: Parameter type for validation
126
- default: Default value
127
- callback: Validation/transformation callback
128
- nargs: Number of arguments (-1 for unlimited)
129
- metavar: Placeholder for help text
130
- expose_value: Whether to pass value to function
131
- is_eager: Process before other parameters
132
- envvar: Environment variable name(s)
133
- autocompletion: Function for shell autocompletion
134
135
Returns:
136
Argument decorator function
137
"""
138
```
139
140
**Usage Examples:**
141
142
```python
143
# Basic argument
144
@click.argument('filename')
145
146
# Multiple arguments
147
@click.argument('files', nargs=-1)
148
149
# Typed argument
150
@click.argument('port', type=int)
151
152
# Optional argument with default
153
@click.argument('output', default='output.txt')
154
```
155
156
### Specialized Option Decorators
157
158
Pre-configured option decorators for common patterns.
159
160
```python { .api }
161
def confirmation_option(
162
*param_decls: str,
163
cls: Type[Option] = Option,
164
help: str = "Confirm the action.",
165
is_flag: bool = True,
166
expose_value: bool = False,
167
prompt: bool | str = False,
168
**kwargs: Any,
169
) -> Callable:
170
"""
171
Decorator for confirmation options (--yes, --force, etc.).
172
173
Parameters:
174
- param_decls: Option declarations
175
- cls: Option class to use
176
- help: Help text
177
- is_flag: Whether this is a boolean flag
178
- expose_value: Whether to pass value to function
179
- prompt: Prompt for confirmation
180
181
Returns:
182
Option decorator function
183
"""
184
185
def password_option(
186
*param_decls: str,
187
cls: Type[Option] = Option,
188
prompt: bool | str = True,
189
hide_input: bool = True,
190
confirmation_prompt: bool = False,
191
**kwargs: Any,
192
) -> Callable:
193
"""
194
Decorator for password input options.
195
196
Parameters:
197
- param_decls: Option declarations
198
- cls: Option class to use
199
- prompt: Prompt for password
200
- hide_input: Hide password input
201
- confirmation_prompt: Require confirmation
202
203
Returns:
204
Option decorator function
205
"""
206
207
def version_option(
208
version: str | None = None,
209
*param_decls: str,
210
cls: Type[Option] = Option,
211
prog_name: str | None = None,
212
message: str | None = None,
213
is_flag: bool = True,
214
**kwargs: Any,
215
) -> Callable:
216
"""
217
Decorator for version display options.
218
219
Parameters:
220
- version: Version string or callable
221
- param_decls: Option declarations
222
- cls: Option class to use
223
- prog_name: Program name for display
224
- message: Custom version message format
225
- is_flag: Whether this is a boolean flag
226
227
Returns:
228
Option decorator function
229
"""
230
231
def help_option(
232
*param_decls: str,
233
cls: Type[Option] = Option,
234
help: str = "Show this message and exit.",
235
is_flag: bool = True,
236
**kwargs: Any,
237
) -> Callable:
238
"""
239
Decorator for help display options.
240
241
Parameters:
242
- param_decls: Option declarations
243
- cls: Option class to use
244
- help: Help text
245
- is_flag: Whether this is a boolean flag
246
247
Returns:
248
Option decorator function
249
"""
250
```
251
252
### Parameter Classes
253
254
Direct parameter classes for programmatic parameter creation.
255
256
```python { .api }
257
class Parameter:
258
param_type_name: str
259
name: str
260
opts: list[str]
261
secondary_opts: list[str]
262
type: ParamType
263
required: bool
264
callback: Callable | None
265
nargs: int
266
multiple: bool
267
expose_value: bool
268
default: Any
269
is_eager: bool
270
metavar: str | None
271
envvar: str | list[str] | None
272
273
def __init__(
274
self,
275
param_decls: Iterable[str] | None = None,
276
type: Any = None,
277
required: bool = False,
278
default: Any | None = None,
279
callback: Callable | None = None,
280
nargs: int | None = None,
281
metavar: str | None = None,
282
expose_value: bool = True,
283
is_eager: bool = False,
284
envvar: str | list[str] | None = None,
285
) -> None:
286
"""
287
Base parameter class.
288
289
Parameters:
290
- param_decls: Parameter declarations
291
- type: Parameter type for validation
292
- required: Whether parameter is required
293
- default: Default value
294
- callback: Validation/transformation callback
295
- nargs: Number of arguments
296
- metavar: Placeholder for help text
297
- expose_value: Whether to pass value to function
298
- is_eager: Process before other parameters
299
- envvar: Environment variable name(s)
300
"""
301
302
def get_default(self, ctx: Context) -> Any: ...
303
def type_cast_value(self, ctx: Context, value: Any) -> Any: ...
304
def process_value(self, ctx: Context, value: Any) -> Any: ...
305
def full_process_value(self, ctx: Context, value: Any) -> Any: ...
306
```
307
308
```python { .api }
309
class Option(Parameter):
310
prompt: str
311
confirmation_prompt: bool
312
hide_input: bool
313
is_flag: bool
314
flag_value: Any
315
is_bool_flag: bool
316
count: bool
317
multiple: bool
318
allow_from_autoenv: bool
319
help: str | None
320
hidden: bool
321
show_default: bool
322
show_choices: bool
323
show_envvar: bool
324
325
def __init__(
326
self,
327
param_decls: Iterable[str] | None = None,
328
show_default: bool = False,
329
prompt: bool | str = False,
330
confirmation_prompt: bool = False,
331
hide_input: bool = False,
332
is_flag: bool | None = None,
333
flag_value: Any | None = None,
334
multiple: bool = False,
335
count: bool = False,
336
allow_from_autoenv: bool = True,
337
type: Any = None,
338
help: str | None = None,
339
hidden: bool = False,
340
show_choices: bool = True,
341
show_envvar: bool = False,
342
**attrs: Any,
343
) -> None:
344
"""
345
Option parameter class.
346
347
Parameters:
348
- param_decls: Option declarations
349
- show_default: Show default value in help
350
- prompt: Prompt for value if not provided
351
- confirmation_prompt: Require confirmation
352
- hide_input: Hide input display
353
- is_flag: Whether this is a boolean flag
354
- flag_value: Value when flag is present
355
- multiple: Allow multiple values
356
- count: Count flag occurrences
357
- allow_from_autoenv: Allow environment variable
358
- type: Parameter type
359
- help: Help text
360
- hidden: Hide from help
361
- show_choices: Show choices in help
362
- show_envvar: Show environment variable in help
363
"""
364
365
def prompt_for_value(self, ctx: Context) -> Any: ...
366
```
367
368
```python { .api }
369
class Argument(Parameter):
370
def __init__(
371
self,
372
param_decls: Iterable[str] | None = None,
373
required: bool | None = None,
374
**attrs: Any
375
) -> None:
376
"""
377
Argument parameter class.
378
379
Parameters:
380
- param_decls: Argument declarations
381
- required: Whether argument is required
382
- **attrs: Additional parameter attributes
383
"""
384
```
385
386
## Special Decorators
387
388
Convenience decorators for common parameter patterns and specialized options.
389
390
### Confirmation Option
391
392
Creates a confirmation option that aborts execution if user declines.
393
394
```python { .api }
395
def confirmation_option(
396
*param_decls: str,
397
help: str = 'Confirm the action.',
398
**kwargs: Any,
399
) -> IdentityFunction:
400
"""
401
Add a confirmation option (typically --yes/-y).
402
403
Parameters:
404
- param_decls: Option declarations (defaults to '--yes/-y')
405
- help: Help text for the option
406
- **kwargs: Additional option parameters
407
408
Usage:
409
@click.command()
410
@click.confirmation_option()
411
def dangerous_operation():
412
click.echo("Performing dangerous operation...")
413
414
# Command line usage:
415
# myapp dangerous_operation --yes
416
"""
417
```
418
419
### Password Option
420
421
Creates a password option with hidden input and optional confirmation.
422
423
```python { .api }
424
def password_option(
425
*param_decls: str,
426
confirmation_prompt: bool = False,
427
help: str | None = None,
428
**kwargs: Any,
429
) -> IdentityFunction:
430
"""
431
Add a password option with hidden input.
432
433
Parameters:
434
- param_decls: Option declarations (defaults to '--password')
435
- confirmation_prompt: Require password confirmation
436
- help: Help text for the option
437
- **kwargs: Additional option parameters
438
439
Usage:
440
@click.command()
441
@click.password_option()
442
def login(password):
443
authenticate(password)
444
445
@click.command()
446
@click.password_option(confirmation_prompt=True)
447
def create_user(password):
448
create_user_account(password)
449
"""
450
```
451
452
### Version Option
453
454
Creates a version option that displays version information and exits.
455
456
```python { .api }
457
def version_option(
458
version: str | None = None,
459
*param_decls: str,
460
prog_name: str | None = None,
461
message: str | None = None,
462
help: str = 'Show the version and exit.',
463
**kwargs: Any,
464
) -> IdentityFunction:
465
"""
466
Add a version option that shows version and exits.
467
468
Parameters:
469
- version: Version string (auto-detected if None)
470
- param_decls: Option declarations (defaults to '--version')
471
- prog_name: Program name for display
472
- message: Custom version message format
473
- help: Help text for the option
474
- **kwargs: Additional option parameters
475
476
Usage:
477
@click.command()
478
@click.version_option(version='1.0.0')
479
def cli():
480
click.echo("Hello World!")
481
482
# Custom message format
483
@click.command()
484
@click.version_option(
485
version='2.1.0',
486
prog_name='MyApp',
487
message='%(prog)s version %(version)s'
488
)
489
def cli():
490
pass
491
"""
492
```
493
494
### Help Option
495
496
Creates a help option that displays help text and exits.
497
498
```python { .api }
499
def help_option(
500
*param_decls: str,
501
help: str = 'Show this message and exit.',
502
**kwargs: Any,
503
) -> IdentityFunction:
504
"""
505
Add a help option (typically --help/-h).
506
507
Parameters:
508
- param_decls: Option declarations (defaults to '--help/-h')
509
- help: Help text for the option
510
- **kwargs: Additional option parameters
511
512
Usage:
513
@click.command(add_help_option=False) # Disable auto help
514
@click.help_option('--info', '-i')
515
def cli():
516
click.echo("Custom help option example")
517
"""
518
```
519
520
### Pass Decorators
521
522
Decorators for passing context and objects to command functions.
523
524
```python { .api }
525
def pass_context(f: _T) -> _T:
526
"""
527
Pass the current context as first argument to decorated function.
528
529
Usage:
530
@click.command()
531
@click.pass_context
532
def cli(ctx):
533
click.echo(f"Command: {ctx.info_name}")
534
click.echo(f"Parent: {ctx.parent.info_name if ctx.parent else 'None'}")
535
"""
536
537
def pass_obj(f: _T) -> _T:
538
"""
539
Pass the context object as first argument to decorated function.
540
541
Usage:
542
@click.group()
543
@click.pass_context
544
def cli(ctx):
545
ctx.obj = {'database': 'mydb.sqlite'}
546
547
@cli.command()
548
@click.pass_obj
549
def status(obj):
550
click.echo(f"Database: {obj['database']}")
551
"""
552
553
def make_pass_decorator(object_type: type, ensure: bool = False) -> IdentityFunction:
554
"""
555
Create a custom pass decorator for specific object types.
556
557
Parameters:
558
- object_type: Type of object to pass
559
- ensure: Create object if it doesn't exist
560
561
Usage:
562
pass_database = click.make_pass_decorator(Database)
563
564
@click.command()
565
@pass_database
566
def query(db):
567
results = db.execute("SELECT * FROM users")
568
"""
569
```