trevorld / r-argparse

command-line optional and positional argument parser
GNU General Public License v2.0
103 stars 11 forks source link

Support 'set_defaults()' #43

Closed oliverbothe closed 1 year ago

oliverbothe commented 1 year ago

This is a noob question and I unfortunately do not have a minimal working example.

I struggle with accessing the sub-command from a subparser. That is taking your vignette as an example

> parser$print_help()
usage: PROG [-h] [--foo] {a,b} ...

positional arguments:
  {a,b}       sub-command help
    a         a help
    b         b help

I would like to access whether the user wanted sub-command a or sub-command b. Or rather I would like to connect functions directly to a and b. If I understand the docs for Python's argparse correctly that is possible with set_defaults (compare here).

Would it be possible to include something like this in your R-package or do I simply miss that it is already included?

Sorry, if this is the wrong place to ask this.

trevorld commented 1 year ago

I would like to access whether the user wanted sub-command a or sub-command b.

You can use the dest argument of add_subparsers() to figure out which sub-command was used:

parser = argparse::ArgumentParser()
parser$add_argument('-g', '--global')
subparsers = parser$add_subparsers(dest="subparser_name") # this line changed
foo_parser = subparsers$add_parser('foo')
foo_parser$add_argument('-c', '--count')
bar_parser = subparsers$add_parser('bar')
args = parser$parse_args(c('-g', 'xyz', 'foo', '--count', '42'))
print(args)
$count
[1] "42"

$global
[1] "xyz"

$subparser_name
[1] "foo"

possible with set_defaults (compare here).

Would it be possible to include something like this in your R-package or do I simply miss that it is already included?

I don't think we ever added support for the set_defaults() method. It would need to be added.

trevorld commented 1 year ago

Currently {argparse} is a wrapper around Python's argparse and {argparse} currently doesn't support passing functions back and forth so even if we added support for set_defaults() (which would work with non-function defaults) that particular approach wouldn't currently work.

An alternative approach if using the dest argument of add_subparsers() would be to use a switch statement on the subparser name e.g.:

switch(args$subparser_name,
            foo = foo_fn(args),
            bar = bar_fn(args),
            stop("Unknown subparser")
trevorld commented 1 year ago

On second thought although we don't currently support passing functions back and forth you could pass the function name and then in R simply call get() on the name to get the function e.g. do something like:

get(args$func)(args)

instead of the Pythonic approach you linked to:

args.func(args)