Skip to main content

ddargparse - dataclass driven argparse

test coverage: 100% GitHub Workflow Status PyPI

A small Python library that simplifies command-line argument parsing by leveraging dataclasses. It allows developers to define their command-line interfaces using dataclass fields, making the code more concise and easier to maintain. With ddargparse, you can easily create complex command-line applications with minimal boilerplate code. It puts a particular focus on properly handling type annotations and defaults, minimizing additional required annotation and maintaining interoperability with the standard argparse.

Installation

pip install ddargparse

Usage

Mode a: argparse + dataclasses

Subclass OptionsBase and annotate fields with standard argparse metadata via the dataclasses.field function (help, required, positional, metavar). Then call register_cli_args to populate an ArgumentParser and from_cli_args to instantiate your options from the parsed result.

Step 1: Option dataclass definition

from argparse import ArgumentParser
from dataclasses import dataclass, field
import ddargparse

@dataclass
class Options(ddargparse.OptionsBase):
    inputfile: str = field(
        metadata={"help": "Input file", "positional": True, "metavar": "FILE"},
    )
    verbose: bool = field(
        metadata={"help": "Enable verbose output"},
    )
    tags: list[str] = field(
        default_factory=list,
        metadata={"help": "One or more tags"},
    )

@dataclass
class DoSomethingOptions(ddargparse.OptionsBase):
    threshold: str = field(metadata={"help": "Some threshold"})
    mode: SomeMode = field(default=SomeMode.DEFAULT, metadata={"help": "Mode to be used"})

Step 2: CLI argument parser declaration

parser = ArgumentParser()
# register dataclass options as argparse parser arguments
Options.register_cli_args(parser)
subparsers = parser.add_subparsers(dest="subcommand")
subparser = subparsers.add_parser("do-something")
# register dataclass options as argparse subparser arguments
DoSomethingOptions.register_cli_args(subparser)

Step 3: CLI argument parsing and option dataclass instantiation

args = parser.parse_args()
# obtain instance of dataclass with global options
options = Options.from_parsed_cli_args(args)
match args.subcommand:
    case "do-something":
        # obtain instance of dataclass with subcommand options
        do_something_options = DoSomethingOptions.from_parsed_cli_args(args)

Mode b: dataclass only

In this mode, control over argparse is handed over to ddargparse entirely and happening under the hood. The advantage is that subcommands can be expressed implicitly in the dataclass hierarchy.

Step 1: Option and subcommand dataclass definition

from argparse import ArgumentParser
from dataclasses import dataclass, field
import ddargparse

@dataclass
class Options(ddargparse.OptionsBase):
    "The docstring is used as description in the CLI interface"

    inputfile: str = field(
        metadata={"help": "Input file", "positional": True, "metavar": "FILE"},
    )
    verbose: bool = field(
        metadata={"help": "Enable verbose output"},
    )
    tags: list[str] = field(
        default_factory=list,
        metadata={"help": "One or more tags"},
    )
    subcommand_do_something: DoSomethingOptions | None


class SomeMode(Enum):
    DEFAULT = 0
    FAST = 1


@dataclass
class DoSomethingOptions(ddargparse.OptionsBase):
    """This is the subcommand description
    
    The first line of the subcommand is used as short help, while the full description
    is displayed upon "mytool do-something --help"
    """

    threshold: str = field(metadata={"help": "Some threshold"})
    mode: SomeMode = field(default=SomeMode.DEFAULT, metadata={"help": "Mode to be used"})

Step 2: CLI argument parsing and option dataclass instantiation

Then, the entire hierarchy of options, including automatic determination of the selected subcommand and its options can be obtained via calling parse_argv() on the top-level Options class.

options = Options.from_cli_args()

Features

  • Declare CLI arguments as typed dataclass fields — no repetitive add_argument calls, no need for the type argument. Automatic convertion of field names into kebab-case CLI arguments.
  • Booleans (store_true / store_false), and list arguments (nargs="+") are inferred automatically from the dataclass field definitions.
  • Custom parse methods: define a parse_<field_name>(cls, value: str) classmethod to override the argument type converter.
  • Mark options as positional ("positional": True).
  • Automatic and natural inference whether option is required (no field(default=...) and no | None in type annotation).
  • Choose between append-style (--arg item1 --arg item2 --arg item3) and nargs-style (default, --arg item1 item2 item3) list arguments via register_cli_args(..., list_append=True|False) or parse_argv(list_append=True|False).
  • Proper support for enums: simply specify an enum type and ddargparse handles ensures that proper (lower, kebab-cased) choices are inferred from the enum item names and the correct type is returned.
  • Seamless integration with standard argparse API or dataclass only modes that hides all technical details of the argument parsing.
  • No additional dependencies.

Requirements

  • Python ≥ 3.11

License

See LICENSE.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ddargparse-1.0.0.tar.gz (11.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ddargparse-1.0.0-py3-none-any.whl (9.4 kB view details)

Uploaded Python 3

File details

Details for the file ddargparse-1.0.0.tar.gz.

File metadata

  • Download URL: ddargparse-1.0.0.tar.gz
  • Upload date:
  • Size: 11.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for ddargparse-1.0.0.tar.gz
Algorithm Hash digest
SHA256 5c49e8ee35134383c532a9ca48fa23f60e7a211a521e794188ac6605d843130b
MD5 4aed172eda34d133a01edb732f3788b3
BLAKE2b-256 821e56eac77863f8515e82ff2949c27ac8bd2f60fdc10a0062c3303b9a715be3

See more details on using hashes here.

Provenance

The following attestation bundles were made for ddargparse-1.0.0.tar.gz:

Publisher: release-please.yml on koesterlab/ddargparse

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file ddargparse-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: ddargparse-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 9.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for ddargparse-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ef0bcc0268d0dacb0c69a8481ee9357ed04b96e8b80f98ad1085941011e25333
MD5 9ab7f4c2346268dcda9e7b154d3e94cf
BLAKE2b-256 556636f3ece26ba5793cbf35c3cec580c3cf9a5f59bfb7a4cc75692f3b7b1ec1

See more details on using hashes here.

Provenance

The following attestation bundles were made for ddargparse-1.0.0-py3-none-any.whl:

Publisher: release-please.yml on koesterlab/ddargparse

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

1.0.1

2 files

This release

1.0.0 This release

2 files

0.3.2

2 files

0.3.1

2 files

0.3.0

2 files

0.2.0

2 files

0.1.4

2 files

0.1.3

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page