lebrice / SimpleParsing

Simple, Elegant, Typed Argument Parsing with argparse
MIT License
384 stars 46 forks source link
argparse argparse-alternative argument-parsing dataclasses python

Build Status PyPI version

Simple, Elegant, Typed Argument Parsing

simple-parsing allows you to transform your ugly argparse scripts into beautifully structured, strongly typed little works of art. This isn't a fancy, complicated new command-line tool either, this simply adds new features to plain-old argparse! Using dataclasses, simple-parsing makes it easier to share and reuse command-line arguments - no more copy pasting!

Supports inheritance, nesting, easy serialization to json/yaml, automatic help strings from comments, and much more!

# examples/demo.py
from dataclasses import dataclass
from simple_parsing import ArgumentParser

parser = ArgumentParser()
parser.add_argument("--foo", type=int, default=123, help="foo help")

@dataclass
class Options:
    """ Help string for this group of command-line arguments """
    log_dir: str                # Help string for a required str argument
    learning_rate: float = 1e-4 # Help string for a float argument

parser.add_arguments(Options, dest="options")

args = parser.parse_args()
print("foo:", args.foo)
print("options:", args.options)
$ python examples/demo.py --log_dir logs --foo 123
foo: 123
options: Options(log_dir='logs', learning_rate=0.0001)
$ python examples/demo.py --help
usage: demo.py [-h] [--foo int] --log_dir str [--learning_rate float]

optional arguments:
  -h, --help            show this help message and exit
  --foo int             foo help (default: 123)

Options ['options']:
   Help string for this group of command-line arguments

  --log_dir str         Help string for a required str argument (default:
                        None)
  --learning_rate float
                        Help string for a float argument (default: 0.0001)

(new) Simplified API:

For a simple use-case, where you only want to parse a single dataclass, you can use the simple_parsing.parse or simple_parsing.parse_known_args functions:

options: Options = simple_parsing.parse(Options)
# or:
options, leftover_args = simple_parsing.parse_known_args(Options)

installation

pip install simple-parsing

Examples

API Documentation (Under construction)

Features

Examples:

Additional examples for all the features mentioned above can be found in the examples folder