I mention python’s argparse
as an example but this would apply to any CLI argument parser library for any language. Just generally speaking, at a high level, if there are a lot of optional arguments for my application, should these arguments’ values be set to at least something, even if its a falsy value?
Here’s what I’m talking about.
say the parser code looks something like…
argparse.command_a.add_argument("-a", required=False)
argparse.command_b.add_argument("-b", required=False)
argparse.command_c.add_argument("-c", required=False)
# later in the program when I retrieve the arguments, there's no defaults so in the worst case that
# none of these options are set, my args dictionary is empty
args = parse_args(...) # = {}
# but some code will want to use these option values if they are set (not a given)
# so now the code is littered with code like this
a = args.a if hasattr(args, 'a') else None
...
b = args.get('b')
if b is not None:
...
...
c = args.get('c', None)
I feel like if defaults were provided for all these options, it would eliminate a lot of this fluff. At this point, why not just specify the default to be None
at least?
argparse.command_a.add_argument("-a", required=False, default=None)
Isn’t this better in every aspect? Instead of making the entire rest of the program guess whether a variable exists and handle the possibility that it doesn’t everywhere, I feel that it causes a lot of antipatterns.
In some sense, I think I’m really trying to get at the philosophy of argparse
default values. For what use cases was the default parameter intended?
By the way I’m aware that none of this code will run in python, I was more borrowing from python’s language artifacts but in general this is all still meant to be pseudocode.
2
The premise behind your question is mistaken.
>>> import argparse
>>> p = argparse.ArgumentParser()
>>> p.add_argument('-a')
>>> p.parse_args()
Namespace(a=None)
The -a
argument is already optional by default (you don’t need required=False
), and its default is already None
, ensuring that args.a
exists without any manual intervention.
You have to opt-in to having no default at all.
>>> p.add_argument("-b", default=argparse.SUPPRESS)
>>> p.parse_args()
Namespace(a=None)
So yes, it probably is a good idea to have some default, and argparse
acknowledges that by providing one.
So some clarifications here. To answer this question for python specifically, argparse does in fact default optional argument values to None. Your problem arises from having multiple subcommands that take different arguments, but go through the same code flow. If you pass the same args from subcommands a, b, c that have different options, then you do have to handle each option that is not common across all three. In that workflow, I would recommend backfilling each option that is not guaranteed to exist.
3