Skip to content

subcommand

clap.subcommand

subcommand(cls: type[T]) -> type[T]
subcommand(
    *,
    name: str = ...,
    version: Optional[str] = None,
    long_version: Optional[str] = None,
    aliases: Sequence[str] = ...,
    usage: Optional[str] = ...,
    about: Optional[str] = ...,
    long_about: Optional[str] = ...,
    before_help: Optional[str] = None,
    before_long_help: Optional[str] = ...,
    after_help: Optional[str] = None,
    after_long_help: Optional[str] = ...,
    subcommand_help_heading: Optional[str] = ...,
    subcommand_value_name: Optional[str] = ...,
    color: Optional[ColorChoice] = ...,
    help_styles: Optional[Styles] = ...,
    help_template: Optional[str] = ...,
    max_term_width: Optional[int] = ...,
    propagate_version: bool = False,
    disable_version_flag: bool = False,
    disable_help_flag: bool = False,
    prefix_chars: str = "-",
    fromfile_prefix_chars: Optional[str] = None,
    conflict_handler: str = ...,
    allow_abbrev: bool = ...,
    exit_on_error: bool = ...,
    deprecated: bool = False,
) -> Callable[[type[T]], type[T]]
subcommand(
    cls: Optional[type[T]] = None,
    /,
    *,
    name: Optional[str] = None,
    version: Optional[str] = None,
    long_version: Optional[str] = None,
    usage: Optional[str] = None,
    aliases: Sequence[str] = (),
    about: Optional[str] = None,
    long_about: Optional[str] = None,
    before_help: Optional[str] = None,
    before_long_help: Optional[str] = None,
    after_help: Optional[str] = None,
    after_long_help: Optional[str] = None,
    subcommand_help_heading: str = "Commands",
    subcommand_value_name: str = "COMMAND",
    color: Optional[ColorChoice] = None,
    styles: Optional[Styles] = None,
    help_template: Optional[str] = None,
    max_term_width: Optional[int] = None,
    propagate_version: bool = False,
    disable_version_flag: bool = False,
    disable_help_flag: bool = False,
    prefix_chars: str = "-",
    fromfile_prefix_chars: Optional[str] = None,
    conflict_handler: Optional[str] = None,
    allow_abbrev: Optional[bool] = None,
    exit_on_error: Optional[bool] = None,
    deprecated: bool = False,
) -> Union[type[T], Callable[[type[T]], type[T]]]

Configure a class as a subcommand parser.

Parameters:

  • cls (Optional[type[T]], default: None ) –

    The class to be decorated (when used without parentheses).

  • name (Optional[str], default: None ) –

    Overrides the runtime-determined name of the program.

  • version (Optional[str], default: None ) –

    Sets the version for the short version (-V) and help messages.

  • long_version (Optional[str], default: None ) –

    Sets the version for the long version (--version) and help messages.

  • usage (Optional[str], default: None ) –

    The string describing the program usage. The default is generated from arguments added to parser.

  • aliases (Sequence[str], default: () ) –

    The aliases to this subcommand.

  • about (Optional[str], default: None ) –

    The subcommand's description for the short help (-h).

  • long_about (Optional[str], default: None ) –

    The subcommand's description for the long help (--help).

  • after_help (Optional[str], default: None ) –

    Free-form help text for after auto-generated short help (-h).

  • after_long_help (Optional[str], default: None ) –

    Free-form help text for after auto-generated long help (--help).

  • before_help (Optional[str], default: None ) –

    Free-form help text for before auto-generated short help (-h).

  • before_long_help (Optional[str], default: None ) –

    Free-form help text for before auto-generated long help (--help).

  • subcommand_help_heading (str, default: 'Commands' ) –

    The help heading used for subcommands when printing help.

  • subcommand_value_name (str, default: 'COMMAND' ) –

    The value name used for subcommands when printing usage and help.

  • color (Optional[ColorChoice], default: None ) –

    When to color output.

  • styles (Optional[Styles], default: None ) –

    The styles for help output.

  • help_template (Optional[str], default: None ) –

    The help template to be used, overriding the default format.

  • max_term_width (Optional[int], default: None ) –

    The help output will wrap to min(max_term_width, shutil.get_terminal_size()).

  • propagate_version (bool, default: False ) –

    Whether to use the version of the current command for all subcommands.

  • disable_version_flag (bool, default: False ) –

    Disable the -V and --version flags.

  • disable_help_flag (bool, default: False ) –

    Disable the -h and --help flags.

  • prefix_chars (str, default: '-' ) –

    The set of characters that prefix optional arguments.

  • fromfile_prefix_chars (Optional[str], default: None ) –

    The set of characters that prefix files from which additional arguments should be read.

  • conflict_handler (Optional[str], default: None ) –

    The strategy for resolving conflicting optionals.

  • allow_abbrev (Optional[bool], default: None ) –

    Whether to allow long options to be abbreviated if the abbreviation is unambiguous.

  • exit_on_error (Optional[bool], default: None ) –

    Whether ArgumentParser exits with error info when an error occurs.

  • deprecated (bool, default: False ) –

    Whether this subcommand is deprecated.

Example:

import clap
from typing import Union

@clap.subcommand(aliases=("w", "wat"))
class Watch:
    """Watches an input file and recompiles on changes."""
    ...

@clap.subcommand
class Init:
    """Initializes a new project from a template."""
    ...

@clap.command(name="typst")
class Cli(clap.Parser):
    command: Union[Watch, Init]
    ...
Source code in clap/api.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
def subcommand[T](
    cls: Optional[type[T]] = None,
    /,
    *,
    name: Optional[str] = None,
    version: Optional[str] = None,
    long_version: Optional[str] = None,
    usage: Optional[str] = None,
    aliases: Sequence[str] = (),
    about: Optional[str] = None,
    long_about: Optional[str] = None,
    before_help: Optional[str] = None,
    before_long_help: Optional[str] = None,
    after_help: Optional[str] = None,
    after_long_help: Optional[str] = None,
    subcommand_help_heading: str = "Commands",
    subcommand_value_name: str = "COMMAND",
    color: Optional[ColorChoice] = None,
    styles: Optional[Styles] = None,
    help_template: Optional[str] = None,
    max_term_width: Optional[int] = None,
    propagate_version: bool = False,
    disable_version_flag: bool = False,
    disable_help_flag: bool = False,
    prefix_chars: str = "-",
    fromfile_prefix_chars: Optional[str] = None,
    conflict_handler: Optional[str] = None,
    allow_abbrev: Optional[bool] = None,
    exit_on_error: Optional[bool] = None,
    deprecated: bool = False,
) -> Union[type[T], Callable[[type[T]], type[T]]]:
    """Configure a class as a subcommand parser.

    Args:
        cls: The class to be decorated (when used without parentheses).
        name: Overrides the runtime-determined name of the program.
        version: Sets the version for the short version (`-V`) and help messages.
        long_version: Sets the version for the long version (`--version`) and help messages.
        usage: The string describing the program usage. The default is
            generated from arguments added to parser.
        aliases: The aliases to this subcommand.
        about: The subcommand's description for the short help (`-h`).
        long_about: The subcommand's description for the long help (`--help`).
        after_help: Free-form help text for after auto-generated short help (`-h`).
        after_long_help: Free-form help text for after auto-generated long help (`--help`).
        before_help: Free-form help text for before auto-generated short help (`-h`).
        before_long_help: Free-form help text for before auto-generated long help (`--help`).
        subcommand_help_heading: The help heading used for subcommands when printing help.
        subcommand_value_name: The value name used for subcommands when printing usage and help.
        color: When to color output.
        styles: The styles for help output.
        help_template: The help template to be used, overriding the default format.
        max_term_width: The help output will wrap to `min(max_term_width, shutil.get_terminal_size())`.
        propagate_version: Whether to use the version of the current command for all subcommands.
        disable_version_flag: Disable the `-V` and `--version` flags.
        disable_help_flag: Disable the `-h` and `--help` flags.
        prefix_chars: The set of characters that prefix optional arguments.
        fromfile_prefix_chars: The set of characters that prefix files from
            which additional arguments should be read.
        conflict_handler: The strategy for resolving conflicting optionals.
        allow_abbrev: Whether to allow long options to be abbreviated if the
            abbreviation is unambiguous.
        exit_on_error: Whether `ArgumentParser` exits with error info when an error occurs.
        deprecated: Whether this subcommand is deprecated.

    Example:

    ```python
    import clap
    from typing import Union

    @clap.subcommand(aliases=("w", "wat"))
    class Watch:
        \"""Watches an input file and recompiles on changes.\"""
        ...

    @clap.subcommand
    class Init:
        \"""Initializes a new project from a template.\"""
        ...

    @clap.command(name="typst")
    class Cli(clap.Parser):
        command: Union[Watch, Init]
        ...
    ```
    """
    def wrap(cls: type[T]) -> type[T]:
        nonlocal about, long_about, name
        setattr(cls, _SUBCOMMAND_MARKER, True)
        if name is None:
            name = to_kebab_case(cls.__name__)
        if cls.__doc__ is not None:
            doc_about, doc_long_about = get_help_from_docstring(cls.__doc__.strip())
            if about is None:
                about = doc_about
            if long_about is None:
                long_about = doc_long_about
        command = Command(
            name=name,
            aliases=aliases,
            usage=usage,
            version=version,
            long_version=long_version,
            about=about,
            long_about=long_about,
            before_help=before_help,
            before_long_help=before_long_help,
            after_help=after_help,
            after_long_help=after_long_help,
            subcommand_help_heading=subcommand_help_heading,
            subcommand_value_name=subcommand_value_name,
            color=color,
            styles=styles,
            help_template=help_template,
            max_term_width=max_term_width,
            propagate_version=propagate_version,
            disable_version_flag=disable_version_flag,
            disable_help_flag=disable_help_flag,
            prefix_chars=prefix_chars,
            fromfile_prefix_chars=fromfile_prefix_chars,
            conflict_handler=conflict_handler,
            allow_abbrev=allow_abbrev,
            exit_on_error=exit_on_error,
            deprecated=deprecated
        )
        setattr(cls, _COMMAND_DATA, command)

        # delete default values of fields so that `@dataclass` does not complain
        # about mutable defaults (`Arg`)
        attrs = {}
        for name, _ in cls.__annotations__.items():
            if attr := getattr(cls, name, None):
                attrs[name] = attr
                delattr(cls, name)
        setattr(cls, _SUBCOMMAND_DEFAULTS, attrs)

        return cls

    if cls is None:
        return wrap
    return wrap(cls)