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 yourArgumentParser. - Typed extraction
After
parse_args(), callextract_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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file argparse_type_helper-0.2.4.tar.gz.
File metadata
- Download URL: argparse_type_helper-0.2.4.tar.gz
- Upload date:
- Size: 11.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5ddffba4d9e686a0325c85d8515f530aaa750a78cb776745718a08c66951c84f
|
|
| MD5 |
bcd3cd0cc942fbd659f1e047ebd83ad7
|
|
| BLAKE2b-256 |
6f14b55da6b6f8dcb084bd93cb04e0baece572b07802b3470cb114b0a20525c3
|
Provenance
The following attestation bundles were made for argparse_type_helper-0.2.4.tar.gz:
Publisher:
publish.yml on lljbash/argparse-type-helper
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
argparse_type_helper-0.2.4.tar.gz -
Subject digest:
5ddffba4d9e686a0325c85d8515f530aaa750a78cb776745718a08c66951c84f - Sigstore transparency entry: 764343487
- Sigstore integration time:
-
Permalink:
lljbash/argparse-type-helper@94c8859061dd3b229b023ee22cb96feb1ce8c974 -
Branch / Tag:
refs/tags/v0.2.4 - Owner: https://github.com/lljbash
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@94c8859061dd3b229b023ee22cb96feb1ce8c974 -
Trigger Event:
push
-
Statement type:
File details
Details for the file argparse_type_helper-0.2.4-py3-none-any.whl.
File metadata
- Download URL: argparse_type_helper-0.2.4-py3-none-any.whl
- Upload date:
- Size: 7.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5eea05115bf307b120b13bd60738caf7abee5293ebfdb74d5f26312f0438a01e
|
|
| MD5 |
bd405fbd4574b631549a442422e16f1d
|
|
| BLAKE2b-256 |
d6780044dcd31dc1e5c335931a0c69747b0fd251a6acb4774e0677d43625d394
|
Provenance
The following attestation bundles were made for argparse_type_helper-0.2.4-py3-none-any.whl:
Publisher:
publish.yml on lljbash/argparse-type-helper
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
argparse_type_helper-0.2.4-py3-none-any.whl -
Subject digest:
5eea05115bf307b120b13bd60738caf7abee5293ebfdb74d5f26312f0438a01e - Sigstore transparency entry: 764343493
- Sigstore integration time:
-
Permalink:
lljbash/argparse-type-helper@94c8859061dd3b229b023ee22cb96feb1ce8c974 -
Branch / Tag:
refs/tags/v0.2.4 - Owner: https://github.com/lljbash
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@94c8859061dd3b229b023ee22cb96feb1ce8c974 -
Trigger Event:
push
-
Statement type: