Is there a proper, or at least better, way to get which command-line argument was used to set an Namespace argument (attribute) value?
I am currently using something like this:
>>> import argparse
>>>
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--do-a', '-a',
... default=False, action='store_true',
... dest='process_foo',
... help="Do some awesome a to the thing.")
>>> args = parser.parse_args()
>>>
>>> def get_argument(parser, dest):
... for action in parser._actions:
... if action.dest == dest:
... return action.option_strings[0], action.help
... return dest, ''
...
>>> get_argument(parser, 'process_foo')
('--do-a', 'Do some awesome a to the thing.')
This will probably work in 99% of cases; however, if more than one command-line argument can set process_foo
, this wont work, and accessing a 'hidden' instance attribute (parser._actions
) is kludgy at best. Is there a better way to do this?
I'm adding this to a module that all data science processes inherit which logs environment and other things so that we have better reproducibility. The module in question already auto-logs settings, parameters, command-line arguments, etc. but is not very user friendly in some aspects.