0
# Core Classes and Context Management
1
2
The foundational classes that represent commands, groups, parameters, and execution context, providing the structure for command-line applications. These classes form the backbone of Click's architecture and enable sophisticated CLI functionality.
3
4
## Capabilities
5
6
### Context Management
7
8
The Context class holds command state, parameters, and execution environment, providing access to shared data and command hierarchy.
9
10
```python { .api }
11
class Context:
12
def __init__(self, command, parent=None, info_name=None, obj=None,
13
auto_envvar_prefix=None, default_map=None, terminal_width=None,
14
max_content_width=None, resilient_parsing=False,
15
allow_extra_args=None, allow_interspersed_args=None,
16
ignore_unknown_options=None, help_option_names=None,
17
token_normalize_func=None, color=None, show_default=None):
18
"""
19
Create a new context.
20
21
Parameters:
22
- command: Command instance this context belongs to
23
- parent: Parent context (for nested commands)
24
- info_name: Descriptive name for documentation
25
- obj: User object for sharing data between commands
26
- auto_envvar_prefix: Prefix for automatic environment variables
27
- default_map: Dict of parameter defaults
28
- terminal_width: Width of terminal for formatting
29
- max_content_width: Maximum width for help content
30
- resilient_parsing: Continue parsing on errors
31
- allow_extra_args: Allow extra arguments
32
- allow_interspersed_args: Allow interspersed arguments and options
33
- ignore_unknown_options: Ignore unknown options
34
- help_option_names: Names for help options
35
- token_normalize_func: Function to normalize option names
36
- color: Enable/disable color output
37
- show_default: Show default values in help
38
"""
39
40
def find_root(self):
41
"""Find the outermost context in the hierarchy."""
42
43
def find_object(self, object_type):
44
"""Find the closest object of given type in context hierarchy."""
45
46
def ensure_object(self, object_type):
47
"""Find object or create if missing."""
48
49
def lookup_default(self, name, call=True):
50
"""Get default value from default_map."""
51
52
def fail(self, message):
53
"""Abort execution with error message."""
54
55
def abort(self):
56
"""Abort the script execution."""
57
58
def exit(self, code=0):
59
"""Exit with specified code."""
60
61
def get_usage(self):
62
"""Get formatted usage string."""
63
64
def get_help(self):
65
"""Get formatted help page."""
66
67
def invoke(self, callback, *args, **kwargs):
68
"""Invoke a callback or command."""
69
70
def forward(self, cmd, *args, **kwargs):
71
"""Forward execution to another command."""
72
```
73
74
**Usage Examples:**
75
76
```python
77
@click.group()
78
@click.pass_context
79
def cli(ctx):
80
"""Main CLI group."""
81
ctx.ensure_object(dict)
82
ctx.obj['database_url'] = 'sqlite:///app.db'
83
84
@cli.command()
85
@click.pass_context
86
def status(ctx):
87
"""Show application status."""
88
db_url = ctx.obj['database_url']
89
click.echo(f'Database: {db_url}')
90
91
# Access parent context
92
if ctx.parent:
93
click.echo(f'Parent command: {ctx.parent.info_name}')
94
```
95
96
### Command Classes
97
98
Basic command structures for creating executable CLI commands.
99
100
```python { .api }
101
class Command:
102
def __init__(self, name, context_settings=None, callback=None, params=None,
103
help=None, epilog=None, short_help=None, options_metavar="[OPTIONS]",
104
add_help_option=True, no_args_is_help=False, hidden=False,
105
deprecated=False):
106
"""
107
Create a command.
108
109
Parameters:
110
- name: Command name
111
- context_settings: Dict with default context settings
112
- callback: Function to execute when command is invoked
113
- params: List of parameters (options/arguments)
114
- help: Help text for the command
115
- epilog: Text shown after help
116
- short_help: Short help for command listings
117
- options_metavar: How to show options in usage
118
- add_help_option: Whether to add --help option
119
- no_args_is_help: Show help when no arguments given
120
- hidden: Hide from help listings
121
- deprecated: Mark as deprecated
122
"""
123
124
def main(self, args=None, prog_name=None, complete_var=None,
125
standalone_mode=True, **extra):
126
"""
127
Main entry point for the command.
128
129
Parameters:
130
- args: Arguments to parse (defaults to sys.argv)
131
- prog_name: Program name
132
- complete_var: Environment variable for shell completion
133
- standalone_mode: Handle exceptions and exit
134
"""
135
136
def make_context(self, info_name, args, parent=None, **extra):
137
"""Create a context for this command."""
138
139
def invoke(self, ctx):
140
"""Invoke the command callback."""
141
142
def get_help(self, ctx):
143
"""Get formatted help text."""
144
145
def get_usage(self, ctx):
146
"""Get formatted usage line."""
147
148
def get_params(self, ctx):
149
"""Get all parameters including help option."""
150
151
class Group(Command):
152
def __init__(self, name=None, commands=None, invoke_without_command=False,
153
no_args_is_help=None, subcommand_metavar=None, chain=False,
154
result_callback=None, **kwargs):
155
"""
156
Create a command group.
157
158
Parameters:
159
- name: Group name
160
- commands: Dict of initial subcommands
161
- invoke_without_command: Invoke group callback without subcommand
162
- no_args_is_help: Show help when no arguments provided
163
- subcommand_metavar: How to represent subcommands in help
164
- chain: Allow chaining multiple subcommands
165
- result_callback: Callback for processing command results
166
"""
167
168
def add_command(self, cmd, name=None):
169
"""Register a command with this group."""
170
171
def command(self, *args, **kwargs):
172
"""Decorator to create and register a command."""
173
174
def group(self, *args, **kwargs):
175
"""Decorator to create and register a subgroup."""
176
177
def get_command(self, ctx, cmd_name):
178
"""Get a command by name."""
179
180
def list_commands(self, ctx):
181
"""List all available command names."""
182
183
def result_callback(self, replace=False):
184
"""Decorator for result processing callback."""
185
186
class CommandCollection(Group):
187
def __init__(self, name=None, sources=None, **kwargs):
188
"""
189
Create a command collection from multiple groups.
190
191
Parameters:
192
- name: Collection name
193
- sources: List of Groups to collect commands from
194
"""
195
196
def add_source(self, group):
197
"""Add a group as a source of commands."""
198
```
199
200
**Usage Examples:**
201
202
```python
203
# Basic command
204
@click.command()
205
@click.option('--verbose', is_flag=True)
206
def simple_command(verbose):
207
"""A simple command example."""
208
if verbose:
209
click.echo('Verbose mode enabled')
210
211
# Command group
212
@click.group()
213
def database():
214
"""Database management commands."""
215
pass
216
217
@database.command()
218
def init():
219
"""Initialize database."""
220
click.echo('Database initialized')
221
222
@database.command()
223
def migrate():
224
"""Run database migrations."""
225
click.echo('Running migrations...')
226
227
# Command collection
228
users_cli = click.Group(name='users')
229
admin_cli = click.Group(name='admin')
230
231
@users_cli.command()
232
def list_users():
233
"""List all users."""
234
click.echo('Listing users...')
235
236
@admin_cli.command()
237
def backup():
238
"""Create backup."""
239
click.echo('Creating backup...')
240
241
# Combine groups
242
main_cli = click.CommandCollection(sources=[users_cli, admin_cli])
243
```
244
245
### Parameter Classes
246
247
Base classes for handling command-line parameters with validation and type conversion.
248
249
```python { .api }
250
class Parameter:
251
def __init__(self, param_decls=None, type=None, required=False, default=None,
252
callback=None, nargs=None, multiple=False, metavar=None,
253
expose_value=True, is_eager=False, envvar=None, shell_complete=None,
254
deprecated=False):
255
"""
256
Base parameter class.
257
258
Parameters:
259
- param_decls: Parameter declarations (names/flags)
260
- type: ParamType for validation and conversion
261
- required: Whether parameter is required
262
- default: Default value
263
- callback: Function to process the value
264
- nargs: Number of arguments to consume
265
- multiple: Accept multiple values
266
- metavar: How to display in help
267
- expose_value: Store value in context.params
268
- is_eager: Process before non-eager parameters
269
- envvar: Environment variable name(s)
270
- shell_complete: Shell completion function
271
- deprecated: Mark as deprecated
272
"""
273
274
def get_default(self, ctx, call=True):
275
"""Get the default value for this parameter."""
276
277
def type_cast_value(self, ctx, value):
278
"""Convert and validate the value."""
279
280
def process_value(self, ctx, value):
281
"""Process value with type conversion and callback."""
282
283
def resolve_envvar_value(self, ctx):
284
"""Find value from environment variables."""
285
286
class Option(Parameter):
287
def __init__(self, param_decls=None, show_default=None, prompt=False,
288
confirmation_prompt=False, prompt_required=True, hide_input=False,
289
is_flag=None, flag_value=None, multiple=False, count=False,
290
allow_from_autoenv=True, type=None, help=None, hidden=False,
291
show_choices=True, show_envvar=False, deprecated=False, **attrs):
292
"""
293
Command-line option parameter.
294
295
Parameters:
296
- param_decls: Option flags (e.g., '--verbose', '-v')
297
- show_default: Show default value in help
298
- prompt: Prompt for value if not provided
299
- confirmation_prompt: Prompt for confirmation
300
- prompt_required: Whether prompt is required
301
- hide_input: Hide input when prompting
302
- is_flag: Treat as boolean flag
303
- flag_value: Value when flag is present
304
- multiple: Allow multiple values
305
- count: Count number of times option is used
306
- allow_from_autoenv: Allow automatic environment variables
307
- help: Help text for the option
308
- hidden: Hide from help output
309
- show_choices: Show choices in help
310
- show_envvar: Show environment variable in help
311
"""
312
313
def prompt_for_value(self, ctx):
314
"""Prompt user for the value."""
315
316
class Argument(Parameter):
317
def __init__(self, param_decls, required=None, **attrs):
318
"""
319
Positional command-line argument.
320
321
Parameters:
322
- param_decls: Argument name
323
- required: Whether argument is required (default True)
324
"""
325
```
326
327
**Usage Examples:**
328
329
```python
330
# Custom parameter with callback
331
def validate_port(ctx, param, value):
332
"""Validate port number."""
333
if value < 1 or value > 65535:
334
raise click.BadParameter('Port must be between 1 and 65535')
335
return value
336
337
@click.command()
338
@click.option('--port', type=int, default=8080, callback=validate_port)
339
def server(port):
340
"""Start server on specified port."""
341
click.echo(f'Starting server on port {port}')
342
343
# Environment variable support
344
@click.command()
345
@click.option('--debug', is_flag=True, envvar='DEBUG')
346
@click.argument('config_file', envvar='CONFIG_FILE')
347
def run(debug, config_file):
348
"""Run application with config."""
349
click.echo(f'Debug: {debug}, Config: {config_file}')
350
```