1

After I've created my argument parser. How can I check if the parser contains a rule for an argument. Here's some code to explain what I mean.

from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument('--foo')
parser.add_argument('--bar')

'foo' in parser
# => True
'bar' in parser
 # => True
'baz' in parser
 # => False

In short, I want to know if an argument exists in the parser.

As part of my program initialisation I am loading several configuration files. If there are settings in the config files which are not in the parser I want to warn the user.

AnnanFay
  • 9,573
  • 15
  • 63
  • 86
  • 1
    http://stackoverflow.com/questions/39996295/correct-way-to-get-allowed-arguments-from-argumentparser should help. – hpaulj Oct 14 '16 at 19:11
  • @hpaulj Thanks! I don't know why that question didn't appear when I searched. I've marked this as a duplicate. – AnnanFay Oct 14 '16 at 19:16

1 Answers1

0

It's a bit clunky, but you could run parse_args with not arguments and extract the keys for the resulting Namespace object:

>>> 'foo' in vars(parser.parse_args())
True
>>> 'baz' in vars(parser.parse_args())
False
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Thanks for responding. One problem with this in my case is I'm using `default=argparse.SUPPRESS` so settings which a user doesn't specify won't overwrite the config files. I've closed the question as it appears to be a duplicate - and the other question has quite a few answers. – AnnanFay Oct 14 '16 at 19:20