C compilers have the -D
switch to define a preprocessor constant at compilation time. It is called like -D name=value
, or -D name
and value
defaults to 1.
Can a similar thing be done with python argparse? That is, can you create an option that meets these criteria?
- The argument can be accepted multiple times
- The argument takes a key-value pair
- If the key is present but the value is not it should use the default
- The result is a mapping (Python dict or similar)
Desired usage:
ap = argparse.ArgumentParser()
ap.add_argument("-D",
#### what goes here ? ####
default=1
)
ap.parse_args(["-D", "foo=bar", "-D", "baz"])
# ==> Namespace(D={'foo': 'bar', 'baz': 1})
If I just use nargs="append"
, I can not specify an automatic default in the add_argument call, and I additionally have to do the string processing myself on the resultant list, which is kind of hairy, and I would like to avoid that.
1