Search code examples
pythoninheritancedefaultparentargparse

ArgParse Python Module: Change default argument value for inherted argument


I have a bunch of Python scripts that use common code for reading input and writing output files of different types.

These are chemical structure files. Some example file types would be .smi or .sdf.

By default, I want some of these scripts to output data in the "smi" file format, and others to output data in the "sdf" format.

Is it possible to override the default value of an argument inherited from a parent parser?

For example...

# Inherited code
filesParser = argparse.ArgumentParser(add_help=False)
filesParser.add_argument('-o', dest='outformat', default="smi")

# Script code
parser = argparse.ArgumentParser(description='inherts from filesParser', parents=[filesParser])
parser.add_argument('--foo')

# Something like...
# parser.outformat.default = "sdf"

args = parser.parse_args()

First post so hope my etiquette is OK.

Many thanks, Dave


Solution

  • Yes (docs):

    >>> parser.parse_args([])
    Namespace(foo=None, outformat='smi')
    >>> parser.set_defaults(outformat='sdf')
    >>> parser.parse_args([])
    Namespace(foo=None, outformat='sdf')