Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Know if an argument has been specified by user when using Python's argparse

Let's say I have a python test using argparse, with several arguments:

  • IP (default: 127.0.0.1)
  • enabled_features (default: [A, B, C])

Sometimes, I'd like to change the default enabled_features, let's say to [A,B,C,D]:

  • depending on something I need the IP to find out (so it can't really be a default value in the way argparse has default values)
  • only if the user hasn't specified the "enabled_features"... that's what I have trouble to know!

So is there an attribute in the argparse classes to know, after:

opts = parser.parse_args()

...that an argument was actually specified by the user, i.e. that one has used something like:

$ python my_test.py --enabled_features A B C

and not:

$ python my_test.py

Thanks!

like image 751
Mathias Avatar asked Oct 21 '22 16:10

Mathias


1 Answers

opts contains all the information that argparse can give you. So you have to either test for some default value (most commonly None), or the absence of the attribute (if default=argparse.SUPPRESS).

Another approach is to specify a reasonable default, and not worry whether the user specified those, or other values, in the input. Which is more important, that the user specified the values, or the values themselves?

like image 100
hpaulj Avatar answered Oct 23 '22 10:10

hpaulj