Programming
python default-value argparse
Updated Tue, 12 Jul 2022 12:22:08 GMT

argparse: setting optional argument with value of mandatory argument


With Python's argparse, I would like to add an optional argument that, if not given, gets the value of another (mandatory) argument.

parser.add_argument('filename',
                    metavar = 'FILE',
                    type    = str,
                    help    = 'input file'
                    )
parser.add_argument('--extra-file', '-f',
                    metavar = 'ANOTHER_FILE',
                    type    = str,
                    default = ,
                    help    = 'complementary file (default: FILE)'
                    )

I could of course manually check for None after the arguments are parsed, but isn't there a more pythonic way of doing this?




Solution

As far as I know, there is no way to do this that is more clean than:

ns = parser.parse_args()
ns.extra_file = ns.extra_file if ns.extra_file else ns.filename

(just like you propose in your question).

You could probably do some custom action gymnastics similar to this, but I really don't think that would be worthwhile (or "pythonic").





Comments (2)

  • +0ns.extra_file = ns.extra_file or ns.filename — Aug 17, 2012 at 15:21  
  • +1 – @kindall this works for filenames, but imagine doing this for an optional boolean argument that has been set to False by the user. You might check for None. — Dec 25, 2019 at 21:25  


External Links

External links referenced by this document: