Search code examples
pythonpython-2.7subclassargparse

How do I subclass argparse.Action to add a custom action?


I have a command line script I'm trying to run that inserts a default value into the Namespace if the value is absent, or takes the supplied argument as is if it's present.

So I want to do this:

myscript.py --merge

Would result in the argument parser Namespace looking like this:

Namespace(merge='--merge')

Else, if I call

myscript.py

Namespace should look like this:

Namespace(merge='DONTMERGE')

I think I need to subclass the argparse.Action class's __call__ method to perform a custom action as specified here: https://pymotw.com/2/argparse/ but I'm unable to figure out how to do this.

I thought something like this would do the trick:

class CustomAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        if isinstance(self.values, None):
            self.values = 'NOMERGE'
        else:
            self.values = '--nomerge'
        setattr(namespace, self.dest, values)

Unfortunately, I'm not getting the expected result.


Solution

  • I think you just need a normal store_const argument.

    parser.add_argument('--merge', action='store_const', const='MERGE', default='DONTMERGE')
    

    If you call your script with --merge, the merge argument takes the value MERGE (specified above as const). Otherwise, the merge argument takes the value DONTMERGE (specified above as default).

    See https://docs.python.org/2/library/argparse.html#action