argparse and subparsers

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Jun 27 06:28:49 EDT 2016


On Monday 27 June 2016 15:34, Lawrence D’Oliveiro wrote:

> On Monday, June 27, 2016 at 4:56:10 PM UTC+12, Sachin Garg wrote:
> 
>> # Set verbose flag
>> verbose = False
>> if arguments['--verbose']:
>>     verbose = True
>> elif arguments['-q']:
>>     verbose = False
> 
> Don’t you just love code (and commenting) like this...


Not particularly, but what are you going to do? You need to support a minimum 
of three cases:

- a default setting;
- the case where the user passes --verbose;
- the case where the user passes -q;

(I'm not sure why --verbose take a long argument but no short argument -v; and 
likewise why there's a -q short argument but no --quiet long version. Oh well.)

A simple test-and-set for each argument is the simplest, most straight-forward 
way of handling this. It's not *pretty* or *elegant* code, but it is the 
easiest to read, write and comprehend, and in my opinion much better than 
alternatives involving ever more arcane method calls to ever more complicated 
classes.

I don't have experience with docutils and cannot judge whether or not Sachin's 
snippets are good or bad examples of use, but find myself going back to the 
good old fashioned GNU style command line parser whenever I need a few command 
line options. If you find yourself writing subparsers and "mandatory options" 
and needing entire help screens to describe single arguments (as in "foo --help 
arg") then really I think you should give up the pretence that you're dealing 
with command line options, and you should write a mini-language for your 
application.

(hg, git, memcoder, soc etc. I'm talking about you.)



-- 
Steve



More information about the Python-list mailing list