Suppose I have an argparse python script:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--foo", required=True)
Now I want to add another option --bar, which would default to appending "_BAR" to whatever was specified by --foo argument.
My goal:
>>> parser.parse_args(['--foo', 'FOO'])
>>> Namespace(foo='FOO', bar="FOO_BAR")
AND
>>> parser.parse_args(['--foo', 'FOO', '--bar', 'BAR'])
>>> Namespace(foo='FOO', bar="BAR")
I need something like this:
parser.add_argument("--bar", default=get_optional_foo + "_BAR")
Here's another attempt at writing a custom Action class
Note that the class has to know the
dest
of the--bar
argument. Also I use a'%s_BAR'
to readily distinguish between a default value, and a non default one. This handles the case where--bar
appears before--foo
.Things that complicate this approach are:
add_argument
time.parse_args
.Action
class is not designed to handle interacting arguments.bar
action will not be called in the default case.bar
default could be a function, but something would have to check afterparse_args
whether it needs to be evaluated or not.While this custom Action does the trick, I still think the
addbar
function in my other answer is a cleaner solution.I would, as a first try, get this working using an after-argparse function.
If this action needs to be reflected in the
help
, put it there yourself.In theory you could write a custom
Action
forfoo
that would set the value of thebar
value as well. But that requires more familiarity with theAction
class.I tried a custom
Action
that tweaks thedefault
of thebar
action, but that is tricky.parse_args
uses the defaults right at the start, before it has acted on any of the arguments.