Click Group Chained Subcommands

Build chained Click subcommands where multiple steps run in sequence, sharing a result context and enforcing invocation order.

PythonCli Tooling

Code

pythonsnippet
42 lines
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 early raise when 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

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.