argparse zero-length switch

Carl Banks pavlovevidence at gmail.com
Sat Oct 15 23:29:40 EDT 2011


On Friday, October 14, 2011 12:41:26 AM UTC-7, Peter Otten wrote:
> Carl Banks wrote:
> 
> > Is it possible to specify a zero-length switch?  Here's what I mean.
> > 
> > I have a use case where some users would have to enter a section name on
> > the command line almost every time, whereas other users (the ones using
> > only one section) will never have to enter the section name.  I don't want
> > to burden users with only one "section" to always enter the section name
> > as a required argument, but I also want to make it as convenient as
> > possible to enter the section name for those who need to.
> > 
> > My thought, on the thinking that practicality beats purity, was to create
> > a zero-length switch using a different prefix character (say, @) to
> > indicate the section name.  So instead of typing this:
> > 
> >    sp subcommand -s abc foo bar
> > 
> > they could type this:
> > 
> >    sp subcommand @abc foo bar
> > 
> > Admittedly a small benefit.  I tried the following but argparse doesn't
> > seem to do what I'd hoped:
> > 
> >    p = argparse.ArgumentParser(prefix_chars='-@')
> >    p.add_argument('@',type=str,dest='section')
> >    ar = p.parse_args(['@abc'])
> > 
> > This throws an exception claiming unrecognized arguments.
> > 
> > Is there a way (that's not a hack) to do this?  Since the current behavior
> > of the above code seems to do nothing useful, it could be added to
> > argparse with very low risk of backwards incompatibility.
> 
> If the number of positional arguments is otherwise fixed you could make 
> section a positional argument with nargs="?"

The positional arguments aren't fixed, otherwise I would have done it that way.  I ended up deciding to prescan the command line for arguments starting with @, and that actually has some benefits over doing it with argparse.  (One little surprise is if you pass it something like "-x @abc foo", where foo is the argument of -x.)

I don't really care for or agree with Steven and Ben Finney's foolish consistency.  I already weighed it against the benefits of consistency, and decided that this parameter was easily important enough to warrant special treatment.  It's actually a good thing for this parameter to look different from other switches; it marks it as specially important.


Carl Banks



More information about the Python-list mailing list