Skip to main content

Nested arguments parser

Project description

nestargs

nestargs is a Python library that treats command line arguments as a hierarchical structure. The functionality for interpreting command line arguments is the same as argparse.

PyPI PyPI - Python Version Python Tests codecov pre-commit.ci status

Installation

pip install nestargs

Basic usage

When defining command line arguments, use "." as the delimiter. to represent a variable hierarchy. The following code example defines an n and price variable in the apple hierarchy and another separate n and price variable in the banana hierarchy.

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))

Variables obtained by parsing command line arguments can be referenced by hierarchy.

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

Of course, you can also refer directly to variables lower down in the hierarchy.

args.apple.price
# => 1.5

When referring to each level of hierarchy, you can use vars to create a dictionary format.

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

Use a different delimiter for namespace

The default namespace delimiter is "." but can be any other character. In that case, specify the delimiter in the NestedArgumentParser constructor argument.

import nestargs

parser = nestargs.NestedArgumentParser(delimiter="/")
parser.add_argument("--apple/n", type=int)

args = parser.parse_args(["--apple/n=1"])
# => _NestedNamespace(apple=_NestedNamespace(n=1))

However, references to variables must be separated by "." delimiter when referring to variables.

args.apple.n
# => 1

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-1.1.0.tar.gz (6.1 kB view hashes)

Uploaded Source

Built Distribution

nestargs-1.1.0-py3-none-any.whl (4.2 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