0

I am using argparse to parse user args. There are defaults provided for each argument, but due to my special need, I would need to also get a list of args that are specified by the user.

Example:

parser = argparse.ArgumentParser(description="Generic Program")
parser.add_argument('-a', type=int, default=1, )
parser.add_argument('-b', type=int, default=2, )
parser.add_argument('-c', type=int, default=3, )
args = parser.parse_args()

Calling:

main.py -a 1 -b 2

I would like to know that the user actually only specified -a and -b but not -c. I cannot seem to see how that is done through the argparse official docs. Using sys.argv would've been too low level and too messy to deal with the raw parsing.

Bonk
  • 1,859
  • 9
  • 28
  • 46
  • 1
    see https://stackoverflow.com/questions/30678187/can-i-check-if-a-value-was-supplied-by-the-default-or-by-the-user – balderman Oct 26 '20 at 17:06
  • The default default is `None` which the user cannot supply. Therefore `args.a` is None` is a reliable test. – hpaulj Oct 26 '20 at 17:22
  • 1
    `parse_args` does maintain a list (or is a set?) of arguments which were 'seen', but that is not available to you. I've explored ways of changing the source code to make that available, but so far haven't come up with anything that's simple and clear. – hpaulj Oct 26 '20 at 18:52

1 Answers1

1

Don't supply a default. You can set the value to 3 once you have determined that it was unset. This adds more work for you, but it seems like the easiest way to do what you are asking.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • This is what I have opted to do for the time being, although I find it strange that ArgumentParser doesn't expose a list of args supplied by the user. – Bonk Oct 27 '20 at 06:59