Skip to content

Cli base class

The class-first alternative to passing schema= on every call, keeping the usage and the fields together on one class. See the Cli base class guide.

Cli

Cli(**fields: Any)

Optional typed base class for a class-first API.

Subclass it, set __cli_doc__ to the usage message, and declare fields as annotations. YourClass.parse(argv) returns an instance typed as the subclass.

It is deliberately a base class rather than a method-injecting decorator, which would degrade the result to Any. This keeps real static types under mypy, pyright and ty.

Source code in src/docopt2/_core.py
def __init__(self, **fields: Any) -> None:
    # Generic value-object init so a plain (non-dataclass) subclass constructs from
    # the bound fields; a @dataclass subclass overrides this with its generated init.
    for name, value in fields.items():
        setattr(self, name, value)

parse classmethod

parse(
    argv: list[str] | tuple[str, ...] | str | None = None,
    *,
    help: bool = True,
    version: object = None,
    options_first: bool = False,
    suggest: bool = False,
    negative_numbers: bool = False,
    allow_abbrev: bool = True,
    allow_extra: bool = False,
    exit_code: int = 1,
    complete: bool = True,
    config: Mapping[str, Any] | None = None,
    help_style: str = "raw",
) -> CliT

Parse argv against __cli_doc__ and return a typed instance of the subclass.

Source code in src/docopt2/_core.py
@classmethod
def parse(
    cls: type[CliT],
    argv: list[str] | tuple[str, ...] | str | None = None,
    *,
    help: bool = True,  # noqa: A002 - mirrors docopt()'s public parameter name
    version: object = None,
    options_first: bool = False,
    suggest: bool = False,
    negative_numbers: bool = False,
    allow_abbrev: bool = True,
    allow_extra: bool = False,
    exit_code: int = 1,
    complete: bool = True,
    config: Mapping[str, Any] | None = None,
    help_style: str = "raw",
) -> CliT:
    """Parse ``argv`` against ``__cli_doc__`` and return a typed instance of the subclass."""
    return docopt(
        cls.__cli_doc__,
        argv,
        help,
        version,
        options_first,
        suggest=suggest,
        negative_numbers=negative_numbers,
        allow_abbrev=allow_abbrev,
        allow_extra=allow_extra,
        exit_code=exit_code,
        complete=complete,
        schema=cls,
        config=config,
        help_style=help_style,
    )