Click Group Chained Subcommands
Build chained Click subcommands where multiple steps run in sequence, sharing a result context and enforcing invocation order.
Code
import click
@click.group(chain=True)
@click.option('--verbose', is_flag=True, help='enable verbose output')
@click.pass_context
def cli(ctx, verbose):
ctx.ensure_object(dict)
ctx.obj['verbose'] = verbose
ctx.obj['results'] = []
@cli.command('extract')
@click.argument('source', type=click.Path(exists=True))
@click.pass_obj
def extract(state, source):
click.echo(f'extracting {source}')
state['results'].append(('extract', source))
@cli.command('transform')
@click.option('--uppercase', is_flag=True)
@click.pass_obj
def transform(state, uppercase):
if not any(step == 'extract' for step, _ in state['results']):
raise click.UsageError('transform must run after extract')
value = 'transformed-data'
if uppercase:
value = value.upper()
state['results'].append(('transform', value))
click.echo(f'transform ok: {value}')
@cli.result_callback()
def process_pipeline(pipeline, state, **kwargs):
click.echo('pipeline finished:')
for step, value in state['results']:
click.echo(f' {step} -> {value}')
if __name__ == '__main__':
cli()How the snippet works
Click Group Chained Subcommands is built around the functions cli, extract, transform and process_pipeline.
Repetition is confined to for step, value in state['results'] — the rest of the file is straight-line. When the guard condition holds, click is thrown rather than a bogus value returned.
What to watch for
- Dependency check:
click— not built-in, must be present in the project. - The guard
not any(step == 'extract' for step, _ in state['results'])short-circuits the flow with an earlyraisewhen its condition holds.
Using it
The entry-point signature is def cli(ctx, verbose)
Key statements
def process_pipeline(pipeline, state, **kwargs):
click.echo('pipeline finished:')
for step, value in state['results']:
click.echo(f' {step} -> {value}')
def extract(state, source):
click.echo(f'extracting {source}')
state['results'].append(('extract', source))
def cli(ctx, verbose):
ctx.ensure_object(dict)
ctx.obj['verbose'] = verbose
ctx.obj['results'] = []
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Is there a failure path for bad input?
- Validation comes first — `click` marks the failure at `not any(step == 'extract' for step, _ in state['results'])`, before any partial work happens.
- What does this need from the package registry?
- These are real dependencies: `click`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.