I have a python program that runs depending on some parameters. Let's say, one of the parameters is C
with a default value of 3
. So when I run it without any arguments, it does
$ python parsing.py
C=3
When I load a file for my initial data, it can get some parameter values from that file. For example if my file MakeC5
says that the program should run with C=5
, I will get
$ python parsing.py --file=MakeC5
C=5
On the other hand, if I specify a different value for C as optional argument, that value is taken, and has priority over the value in the file.
$ python parsing.py --C=4
C=4
$ python parsing.py --file=MakeC5 --C=4
C=4
Up to here, I can just check if the value specified on the command line is different from the default value and otherwise take the one from the file, as with
if parameters.C == parser.get_default('C'):
parameters.C = load_file(parameters.file)["C"]
But this approach does not work if I give the default value for C on the command line as in
$ python parsing.py --file=MakeC5 --C=3
C=3
How do I get that case right? Is there a way that does not need to parse the command line twice as in
parameters = parser.parse_args()
parameters_from_file = load_file(parameters.file)
parser.set_defaults(**parameters_from_file)
parameters = parser.parse_args()
which does not look like “the obvious pythonic way to do this” to me? This is quasi reading a configuration file that can be specified as argument, so I expect there to be a good way.