argparse-subdec 0.2.1

Creator: bradpython12

Last updated:

Add to Cart

Description:

argparsesubdec 0.2.1

This is a very simple Python package that allows one to create argparse’s
subcommands via function decorators.

Usage
Create a SubDec object:
import argparse_subdec

# Create the object to collect subcommands via decorators
sd = argparse_subdec.SubDec()
Now, we can define our subcommands. We define a subcommand by decorating a
function with method calls to sd, like below:
@sd.add_argument('--option', default='123')
@sd.add_argument('--another')
def foo(args):
print(f'foo subcommand: --option={args.option!r} and --another={args.another!r}')
You can use any method name that you would use in a subparser. In our example
above, we used add_argument, probably most commonly used. When creating
the subparsers, sd will replay those calls to the created subparser for
the foo subcommand.
In the example below we define a second subcommand, which will be named
foo-bar:
@sd.cmd(prefix_chars=':')
@sd.add_argument('positional_arg', type=int)
def foo_bar(args):
print(f'foo-bar subcommand: {args.positional_arg!r}')
Note that we use a special decorator, sd.cmd, which makes sd pass all
of its arguments down to add_parser() when creating the subparser for
foo-bar.
Once our subcommands are defined, we must call sd.create_parsers() in
order to effectively create the subparsers:
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
sd.create_parsers(subparsers)
The following is example of how we would call the subcommands:
args = parser.parse_args(['foo', '--another', 'hello'])
args.fn(args) # The subcommand function is assigned to ``args.fn`` by default
# Outputs: foo subcommand: --option='123' and --another='hello'
For more details about the API, check out the subdec module.


Install
Via pip:
pip install argparse-subdec

License

For personal and professional use. You cannot resell or redistribute these repositories in their original state.

Customer Reviews

There are no reviews.