Argparse-Dataclass
argparse-dataclass simplifies creating command-line interfaces by automatically generating `argparse` arguments from Python dataclasses. It uses type hints for argument type inference and supports features like default values, help messages, and argument groups. The current version is 2.0.0, and it generally follows an as-needed release cadence for bug fixes and feature enhancements.
Warnings
- breaking In version 2.0.0, the `ArgumentParser` constructor now expects a dataclass *type* (e.g., `Config`) instead of a dataclass *instance* (e.g., `Config()`).
- breaking The internal attribute `argument_settings` (used for configuring argument parsing behavior within a dataclass) was renamed to `_argument_settings` in version 2.0.0 to signify its internal, non-public nature.
- gotcha `argparse-dataclass` heavily relies on Python type hints to infer the correct `argparse` argument types (e.g., `str`, `int`, `bool`, `list`). Omitting or providing incorrect type hints can lead to unexpected parsing behavior or errors.
- gotcha Boolean dataclass fields automatically generate both `--field` (store `True`) and `--no-field` (store `False`) arguments by default. If you only expect a single flag without its negation, this might be unexpected.
Install
-
pip install argparse-dataclass
Imports
- ArgumentParser
from argparse_dataclass import ArgumentParser
Quickstart
from dataclasses import dataclass
from argparse_dataclass import ArgumentParser
@dataclass
class Config:
input_file: str
output_dir: str = 'output'
verbose: bool = False
port: int = 8080
def main():
parser = ArgumentParser(Config)
config = parser.parse_args(['--input-file', 'data.txt', '--verbose'])
print(f"Input: {config.input_file}, Output: {config.output_dir}, Verbose: {config.verbose}, Port: {config.port}")
if __name__ == '__main__':
main()