In the end, the difference between try, except
and testing len(sys.argv)
isn't all that significant. They're both a bit hackish compared to argparse
.
This occurs to me, though -- as a sort of low-budget argparse:
arg_names = ['command', 'x', 'y', 'operation', 'option']
args = dict(zip(arg_names, sys.argv))
You could even use it to generate a namedtuple
with values that default to None
-- all in four lines!
Arg_list = collections.namedtuple('Arg_list', arg_names)
args = Arg_list(*(args.get(arg, None) for arg in arg_names))
In case you're not familiar with namedtuple
, it's just a tuple that acts like an object, allowing you to access its values using tup.attribute
syntax instead of tup[0]
syntax.
So the first line creates a new namedtuple
type with values for each of the values in arg_names
. The second line passes the values from the args
dictionary, using get
to return a default value when the given argument name doesn't have an associated value in the dictionary.