I'm writing a command-line enhancer program. I chose to do this instead of using optparse
, argparse
, or the others available because: 1) I wanted the experience; and 2) I don't like them. ;)
A simple example:
@Script(
live_daemon=Spec('test the installed daemon', FLAG, None, remove=True),
verbose=Spec('more info on tests', FLAG),
port=Spec('port for daemon to use for mini-tcp server', OPTION, type=int, remove=True),
log=Spec('specific tests to log', MULTI, remove=True),
tests=Spec('specific tests to run', OPTION),
)
def main(live_daemon, verbose, log, port=8079, *tests):
pass
As you can see from the port
option above it is possible to specify the type of the argument that will be passed in to the function; the default type is str
, but any callable is allowed.
One possibility not shown in the above example is a mapping:
@Script( random_vars=('for example', OPTION, type=(str, int)) )
def main(**random_vars):
pass
Deep in the bowels of this utility program is a function that converts the incoming parameters to the default or requested types -- all it has to work with is a list to store the results, the function to use to do the conversion, and the data (which may be a singe item, or two items).
This is the sticky point: the default converter function should correctly handle any number of input items, and simply return them as-is -- rather than have a series of if/else blocks to select the correct default converter... in other words, an identity function.
The two lambdas I have now look like:
lamba x: x
lambda x, y: (x, y)
and what I would really like is a single function:
identity(x) --> x
identity(x, y) --> x, y