Skip to main content

Nested arguments parser

Project description

nestargs

nestargs is a Python library that defines nested program arguments. It is based on argparse.

PyPI PyPI - Python Version Build Status codecov

Read this in Japanese: 日本語

Installation

pip install nestargs

Basic usage

Define program arguments in the same way as argparse. A nested structure can be represented by putting a dot in the program argument name.

import nestargs

parser = nestargs.NestedArgumentParser()

parser.add_argument("--apple.n", type=int)
parser.add_argument("--apple.price", type=float)

parser.add_argument("--banana.n", type=int)
parser.add_argument("--banana.price", type=float)

args = parser.parse_args(
    ["--apple.n=2", "--apple.price=1.5", "--banana.n=3", "--banana.price=3.5"]
)
# => NestedNamespace(apple=NestedNamespace(n=2, price=1.5), banana=NestedNamespace(n=3, price=3.5))

Let's take out only the program argument apple.

args.apple
# => NestedNamespace(n=2, price=1.5)

You can also get each value.

args.apple.price
# => 1.5

If you want a dictionary format, you can get it this way.

vars(args.apple)
# => {'n': 2, 'price': 1.5}

Define program arguments from functions

The function register_arguments can be used to define program arguments from the parameters any function.

In the following example, program arguments with multiple prefixes are defined as the n and price parameters of the function total_price. At this time, the behavior of the program argument is automatically determined according to the default value of the parameter.

import nestargs


def total_price(n=1, price=1.0):
    return n * price


parser = nestargs.NestedArgumentParser()
parser.register_arguments(total_price, prefix="apple")
parser.register_arguments(total_price, prefix="banana")

args = parser.parse_args(
    ["--apple.n=2", "--apple.price=1.5", "--banana.n=3", "--banana.price=3.5"]
)
# => NestedNamespace(apple=NestedNamespace(n=2, price=1.5), banana=NestedNamespace(n=3, price=3.5))

You can call the function with the values obtained from the program arguments as follows:

apple = total_price(**vars(args.apple))
banana = total_price(**vars(args.banana))

print(apple + banana)
# => 13.5

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

nestargs-0.3.0.tar.gz (3.9 kB view hashes)

Uploaded Source

Built Distribution

nestargs-0.3.0-py3-none-any.whl (4.0 kB view hashes)

Uploaded Python 3

Supported by

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