Skip to main content

an easy-to-integrate typed argument parser

Project description

Argparse Type Helper

A lightweight helper that lets you leverage type hints with argparse.

Installation

pip install argparse-type-helper

Features

  • Class-based schema Bundle all your arguments in a single @targs-decorated class.
  • Identical API Each field uses the same parameters as argparse.add_argument (help, action, nargs, etc.).
  • Automatic registration One call to register_targs(parser, YourArgs) wires up all arguments on your ArgumentParser.
  • Typed extraction After parse_args(), call extract_targs() to get a fully-typed instance of your class.
  • Hybrid usage Mix native parser.add_argument(...) calls with class-based definitions in the same parser.
  • Docstring support Use docstrings to automatically generate help text for your arguments.

Why not typed-argparse?

typed-argparse is a great library, but it replaces the familiar argparse.add_argument API with its own argument-definition interface, which can be a hurdle when integrating into an existing codebase.

argparse-type-helper, by contrast, is a simple helper that allows you to use type hints with argparse with minimal learning curve. It uses the same argparse API you’re already familiar with, and you can even mix native argparse usage with class-based definitions in the same parser.

Usage

import argparse
import sys
from typing import Never

from argparse_type_helper import (
    Flag,
    Name,
    extract_targs,
    post_init,
    register_targs,
    targ,
    targs,
)


# Define your typed arguments as a targ class
@targs
class MyArgs:
    # This example will show the common usage of targ.

    positional: str = targ(Name, help="A positional argument (positional).")
    custom_name_pos: str = targ(
        "my_positional", help="A custom named positional argument."
    )

    optional: str = targ(Flag, help="An optional argument (--optional).")
    optional_dash: str = targ(
        Flag, help="underscore is replaced with dash (--optional-dash)."
    )
    optional_short: str = targ(
        Flag("-s"), help="You can also add a short name (-s, --optional-short)."
    )
    custom_name_opt: str = targ(
        "--my-optional",
        help="A custom named optional argument.",
    )
    custom_name_opt_short: str = targ(
        ("-c", "--my-short-optional"),
        help="A custom named optional argument with a short name. (note the tuple)",
    )

    options: list[str] = targ(
        Flag,
        action="extend",
        nargs="+",
        default=[],
        help="All options (`help`, `action`, `nargs`, etc.) are the same as argparse.",
    )
    choices: str = targ(
        Flag,
        choices=["option1", "option2", "option3"],
        help="Another example argument with choices.",
    )
    flag: bool = targ(
        Flag("-d"), action="store_true", help="Another example boolean flag."
    )

    default_type: int = targ(
        Flag,
        default=42,
        help="if type is not specified, it defaults to the type hint. (type=int in this case)",
    )
    custom_type: float = targ(
        Flag,
        type=lambda x: round(float(x), 1),
        default=3.14,
        help="You can also specify a custom type",
    )

    docstring_as_help: str = targ(Flag, default="default value")
    """
    If you don't specify a help, it will use the docstring as the help text.
    This is useful for documentation purposes.
    Your LSP will also pick this up.
    """

    # You can also use the `post_init` decorator to execute some code after the arguments are extracted.
    # This is useful for validation or other post-processing.
    @post_init
    def validate(self) -> None:
        if self.positional == "error":
            raise ValueError("positional argument cannot be 'error'")


# You can register the targs with a custom parser
class MyParser(argparse.ArgumentParser):
    def error(self, message: str) -> Never:
        sys.stderr.write("error: %s\n" % message)
        self.print_help()
        sys.exit(2)


if __name__ == "__main__":
    # Create a parser
    parser = MyParser(description="Process some data arguments.")

    # Register the targs with the parser
    # verbose=True will print the registered arguments
    register_targs(parser, MyArgs, verbose=True)

    # Hybrid usage example
    parser.add_argument("--version", action="version", version="MyArgs 1.0.0")

    # Parse the arguments
    args = parser.parse_args()

    # Extract the targs from the parsed arguments
    my_args = extract_targs(args, MyArgs)
    print(f"Parsed arguments: {my_args}")

Project details


Download files

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

Source Distribution

argparse_type_helper-0.2.2.tar.gz (10.6 kB view details)

Uploaded Source

Built Distribution

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

argparse_type_helper-0.2.2-py3-none-any.whl (7.8 kB view details)

Uploaded Python 3

File details

Details for the file argparse_type_helper-0.2.2.tar.gz.

File metadata

  • Download URL: argparse_type_helper-0.2.2.tar.gz
  • Upload date:
  • Size: 10.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for argparse_type_helper-0.2.2.tar.gz
Algorithm Hash digest
SHA256 4dcb02a3ebb88a32e268bd2f26981b34ad72b6506c77e2a15b17d9ba5b0b5a88
MD5 6b016f05afb012a80acd5466963893fa
BLAKE2b-256 2a077d8ce74a5ea5f0387607d568bb0f70d26e627acaa70676e22421b2d48afa

See more details on using hashes here.

Provenance

The following attestation bundles were made for argparse_type_helper-0.2.2.tar.gz:

Publisher: publish.yml on lljbash/argparse-type-helper

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

File details

Details for the file argparse_type_helper-0.2.2-py3-none-any.whl.

File metadata

File hashes

Hashes for argparse_type_helper-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 bb39d00937aa5434387b17d620400d4e85e733b15116c45d65caa6330b5b4995
MD5 57c7c82333334a9bacb65e4047062077
BLAKE2b-256 5fa18b7d8d0920fd1599ed492bcf7d67b5742b19dc898f9191a8960e233bb7cd

See more details on using hashes here.

Provenance

The following attestation bundles were made for argparse_type_helper-0.2.2-py3-none-any.whl:

Publisher: publish.yml on lljbash/argparse-type-helper

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

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page