{"id":13501230,"url":"https://github.com/DanCardin/cappa","last_synced_at":"2025-03-29T08:32:14.996Z","repository":{"id":194197848,"uuid":"690313976","full_name":"DanCardin/cappa","owner":"DanCardin","description":"Declarative CLI argument parser","archived":false,"fork":false,"pushed_at":"2024-10-24T02:19:11.000Z","size":1599,"stargazers_count":126,"open_issues_count":0,"forks_count":9,"subscribers_count":5,"default_branch":"main","last_synced_at":"2024-10-30T01:37:27.211Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DanCardin.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"DanCardin"}},"created_at":"2023-09-12T00:45:34.000Z","updated_at":"2024-10-24T00:30:24.000Z","dependencies_parsed_at":"2023-09-12T08:38:26.111Z","dependency_job_id":"b95b6728-9651-4b90-9daf-4ea5377f5f99","html_url":"https://github.com/DanCardin/cappa","commit_stats":{"total_commits":154,"total_committers":11,"mean_commits":14.0,"dds":"0.14935064935064934","last_synced_commit":"1334fdad97f253b634e9b4dc4a8a2f079c2b5f8f"},"previous_names":["dancardin/cappa"],"tags_count":75,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DanCardin%2Fcappa","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DanCardin%2Fcappa/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DanCardin%2Fcappa/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DanCardin%2Fcappa/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DanCardin","download_url":"https://codeload.github.com/DanCardin/cappa/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246162092,"owners_count":20733351,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T22:01:29.940Z","updated_at":"2025-03-29T08:32:14.990Z","avatar_url":"https://github.com/DanCardin.png","language":"Python","funding_links":["https://github.com/sponsors/DanCardin"],"categories":["Python"],"sub_categories":[],"readme":"# Cappa\n\n[![Actions Status](https://github.com/DanCardin/cappa/actions/workflows/test.yml/badge.svg)](https://github.com/dancardin/cappa/actions)\n[![codecov](https://codecov.io/gh/DanCardin/cappa/graph/badge.svg?token=jCpAbqWQgU)](https://codecov.io/gh/DanCardin/cappa)\n[![Documentation Status](https://readthedocs.org/projects/cappa/badge/?version=latest)](https://cappa.readthedocs.io/en/latest/?badge=latest)\n\n- [Full Documentation](https://cappa.readthedocs.io/en/latest/)\n- [Comparison vs click/typer/argparse/etc](https://cappa.readthedocs.io/en/latest/comparison.html)\n- [Annotations Inference Docs](https://cappa.readthedocs.io/en/latest/annotation.html)\n- [\"invoke\" API Docs](https://cappa.readthedocs.io/en/latest/invoke.html)\n- [Class Compatibility (dataclasses/pydantic/etc)](https://cappa.readthedocs.io/en/latest/class_compatibility.html)\n\nCappa is a declarative command line parsing library, which uses runtime type inspection\nto infer (default) CLI argument behavior, and provide automatic [help text](https://cappa.readthedocs.io/en/latest/help.html)\ngeneration and dynamic completion generation.\n\nIt supports two different modes of execution:\n\n* `parse`: Argparse-like parsing of the arguments into an output structure\n* [invoke](https://cappa.readthedocs.io/en/latest/invoke.html): Click-like calling\n  of functions based on the selected subcommand\n\n  It also provides a [dependency injection system](https://cappa.readthedocs.io/en/latest/invoke.html#Invoke-Dependencies)\n  for providing non-argument resources to the invoked commands.\n\nAnd, a number of different styles of CLI declaration (which can be mixed and matched within\na given CLI):\n\n* Classes: The fields of the class correspond to CLI arguments/subcommands\n* Functions: The arguments of the function correspond to CLI arguments\n* Methods: The class fields correspond to CLI arguments, and the methods correspond to subcommands\n* Imperative Construction: The CLI structure can be manually/imperitavely constructed,\n  rather than being inferred from the input structure\n\n\u003cdetails open\u003e\n  \u003csummary\u003e\u003ch2\u003eClass Based, parse\u003c/h2\u003e\u003c/summary\u003e\n\n  ```python\n  from dataclasses import dataclass, field\n  import cappa\n  from typing import Literal\n  from typing_extensions import Annotated\n\n  @dataclass\n  class Example:\n      positional_arg: str = \"optional\"\n      boolean_flag: bool = False\n      single_option: Annotated[int | None, cappa.Arg(short=True, help=\"A number\")] = None\n      multiple_option: Annotated[tuple[Literal[\"one\", \"two\", \"three\"]], cappa.Arg(long=True)] = ()\n\n  args: Example = cappa.parse(Example, backend=cappa.backend)\n  print(args)\n  ```\n\n  Produces the following CLI:\n\n  ![help text](./docs/source/_static/example.svg)\n\n  In this way, you can turn any dataclass-like object (with some additional\n  annotations, depending on what you're looking for) into a CLI.\n  \n  You'll note that `cappa.parse` returns an instance of the class. This API should\n  feel very familiar to `argparse`, except that you get the fully typed dataclass\n  instance back instead of a raw `Namespace`.\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003e\u003ch2\u003eClass Based, invoke\u003c/h2\u003e\u003c/summary\u003e\n\n  [\"invoke\" documentation](https://cappa.readthedocs.io/en/latest/invoke.html)\n\n  The \"invoke\" API is meant to feel more like the experience you get when using\n  `click` or `typer`. You can take the same dataclass, but register a function to\n  be called on successful parsing of the command.\n  \n  ```python\n  from dataclasses import dataclass\n  import cappa\n  from typing_extensions import Annotated\n  \n  def function(example: Example):\n      print(example)\n  \n  @cappa.command(invoke=function)\n  class Example:  # identical to original class\n      positional_arg: str\n      boolean_flag: bool\n      single_option: Annotated[int | None, cappa.Arg(long=True)]\n      multiple_option: Annotated[list[str], cappa.Arg(short=True)]\n  \n  \n  cappa.invoke(Example)\n  ```\n  \n  (Note the lack of the dataclass decorator. You can optionally omit or include\n  it, and it will be automatically inferred).\n  \n  Alternatively you can make your dataclass callable, as a shorthand for an\n  explicit invoke function:\n  \n  ```python\n  @dataclass\n  class Example:\n      ...   # identical to original class\n  \n      def __call__(self):\n         print(self)\n  ```\n  \n  Note `invoke=function` can either be a reference to some callable, or a string\n  module-reference to a function (which will get lazily imported and invoked).\n\n  ## Subcommands\n  \n  With a single top-level command, the click-like API isn't particularly valuable\n  by comparison. Click's command-centric API is primarily useful when composing a\n  number of nested subcommands, and dispatching to functions based on the selected\n  subcommand.\n  \n  ```python\n  from __future__ import annotations\n  from dataclasses import dataclass\n  import cappa\n  \n  @dataclass\n  class Example:\n      cmd: cappa.Subcommands[Print | Fail]\n\n  \n  @dataclass\n  class Print:\n      loudly: bool\n\n      def __call__(self):  # again, __call__ is shorthand for the above explicit `invoke=` form.\n          if self.loudly:\n              print(\"PRINTING!\")\n          else:\n              print(\"printing!\")\n  \n  def fail():\n      raise cappa.Exit(code=self.code)\n\n  @cappa.command(invoke=fail)\n  class Fail:\n      code: int\n  \n  cappa.invoke(Example)\n  ```\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003e\u003ch2\u003eFunctions, invoke\u003c/h2\u003e\u003c/summary\u003e\n\n  Purely function-based CLIs **can** reduce the ceremony required to define a given CLI\n  command. Such a CLI is exactly equivalent to a CLI defined as a dataclass with the\n  function's arguments as the dataclass's fields.\n  \n  ```python\n  import cappa\n  from typing_extensions import Annotated\n  \n  def function(foo: int, bar: bool, option: Annotated[str, cappa.Arg(long=True)] = \"opt\"):\n      ...\n  \n  \n  cappa.invoke(function)\n  ```\n  \n  There are, however, some downsides to using functions. Namely, that `function`\n  has no nameable type! As such, a free function can not be easily named as a\n  subcommand option (`Subcommand[Foo | Bar]`).\n\n  You **can** define a root level function with class-based subcommands, but\n  the reverse is not possible because there is no valid type you can supply in\n  the subcommand union.\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003e\u003ch2\u003eMethods, invoke\u003c/h2\u003e\u003c/summary\u003e\n\n  See also [Methods](https://cappa.readthedocs.io/en/latest/functions_and_methods.html#methods).\n\n  ```python\n  from __future__ import annotations\n  from dataclasses import dataclass\n  import cappa\n  \n  @cappa.command\n  @dataclass\n  class Example:\n      arg: int\n\n      @cappa.command\n      def add(self, other: int) -\u003e int:\n          \"\"\"Add two numbers.\"\"\"\n          return self.arg + some_dep\n  \n      @cappa.command(help=\"Subtract two numbers\")\n      def subtract(self, other: int) -\u003e int:\n          return self.arg - other\n  \n  cappa.invoke(Example)\n  ```\n\n  With methods, the enclosing class corresponds to the parent object CLI arguments,\n  exactly like normal class based definition. Unlike with free functions, (explicitly\n  annotated) methods are able to act as subcommands, who's arguments (similarly to free functions)\n  act as the arguments for the subcommand.\n\n  The above example produces a CLI like:\n\n  ```\n  Usage: example ARG {add,subtract} [-h] [--completion COMPLETION]\n\n  Arguments\n    ARG\n\n  Subcommands\n    add                        Add two numbers.\n    subtract                   Subtract two numbers.\n  ```\n\u003c/details\u003e\n\n\n\u003cdetails\u003e\n  \u003csummary\u003e\u003ch2\u003eImperative Construction, parse/invoke\u003c/h2\u003e\u003c/summary\u003e\n\n  See also [Manual Construction](https://cappa.readthedocs.io/en/latest/manual_construction.html).\n\n  ```python\n  from dataclasses import dataclass\n  \n  import cappa\n\n  @dataclass\n  class Foo:\n      bar: str\n      baz: list[int]\n\n  command = cappa.Command(\n      Foo,\n      arguments=[\n          cappa.Arg(field_name=\"bar\"),\n          cappa.Arg(field_name=\"baz\", num_args=2),\n      ],\n      help=\"Short help.\",\n      description=\"Long description.\",\n  )\n\n  result = cappa.parse(command, argv=[\"one\", \"2\", \"3\"])\n  ```\n\n  All other APIs of cappa amount to scanning the provided input structure, and producing\n  a `cappa.Command` structure. As such, it's equally possible for users to manually\n  construct the commands themselves.\n\n  This could also be used to extend cappa, or design even more alternative interfaces\n  ([Cleo](https://github.com/python-poetry/cleo) is another, fairly different, option\n  that comes to mind).\n\u003c/details\u003e\n\n## Inspirations\n\nCredit where credit is due\n\n* The \"Derive\" API of the Rust library [Clap](https://docs.rs/clap/latest/clap/_derive/index.html)\n  directly inspired the concept of mapping a type's fields to the shape of the CLI, by inferring\n  the default behavior from introspecting types.\n\n* Click's easy way of defining large graphs of subcommands and mapping them to functions,\n  inspired the the \"invoke\" API of Cappa. The actual APIs dont particularly resemble one\n  another, but subcommands directly triggering functions (in contrast to argparse/Clap) is\n  a very nice, and natural seeming feature!\n\n* FastAPI's `Depends` system inspired Cappa's dependency injection system. This API is\n  quite natural, and makes it very easy to define a complex system of ad-hoc dependencies\n  **without** the upfront wiring cost of most DI frameworks.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDanCardin%2Fcappa","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FDanCardin%2Fcappa","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDanCardin%2Fcappa/lists"}