Re: Re: Implementing variable number of option arguments

Greg Ward <[email protected]> Thu, 11 Nov 2004 20:11:25 -0500
Newsgroups gmane.comp.python.optik.user
Message-ID <[email protected]>
[me]
>Fourth, specifying leftover positional arguments.  I'm thinking along
>these lines:
>
>  parser = OptionParser(usage="%prog [options] [name1 [name2 [name3]]]")
>  parser.add_option(...)
>  [...]
>  parser.parse_args(minargs=0, maxargs=3, type="string")

For the record, I'm now leaning towards a separate method to specify
positional arguments:

  parser.require_args(minargs=0, maxargs=3, type="string")
  parser.parse_args()

This is implementation-driven: I had forgotten about the hook I snuck in
to allow subclasses to check positional args, OptionParser.check_args().
As soon as I looked at the code, I realized I just need to hijack
check_args() to do the "real" positional argument checking.  Easiest way
to do that is to store the requirements in instance attributes set by a
separate call.  I *think* it's cleaner this way.

[Beni Cherniavsky]
> (0, N) seems good enough to me.  And (N, N) is akwardly more verbose
> this way.  I don't see the gain that justifies 2 yet another options to
> remember.

You mean you want the above example to be

  parser.require_args(nargs=(0, 3), type="string")
  parser.parse_args()

?  Yeah, that's got the benefit of greater consistency and less typing,
especially in the nargs=3 case.  Hmmm... ok, you win.  nargs it is.

[me again]
>The current semantics (which would remain the default) are:
>
>  parser.parse_args(minargs=0, maxargs=sys.maxint, type="string")
>

[Beni]
> Please use None instead of sys.maxint to represent infinity.  I know it
> won't cause problems but it would be cleaner and more consistent with
> Python traditions (e.g. in slices).

[rummage ... dig ... read ...]  Hmmm!  I did not know that these:

  somelist[5:]
  somelist[5:None]

were equivalent!  But here's something weird: if I write a subclass of
list, eg.

class mylist(list):
  def __getslice__(self, a, b):
    print a, b
    return super(mylist, self).__getslice__(a, b)

it reveals that

  somelist[5:]

actually calls

  somelist.__getslice__(5, 2147483647)

Cool.  OK, I'll let None mean infinity.  Simple enough, I think.

        Greg
-- 
Greg Ward <[email protected]>                         http://www.gerg.ca/
MTV -- get off the air!
    -- Dead Kennedys


-------------------------------------------------------
This SF.Net email is sponsored by:
Sybase ASE Linux Express Edition - download now for FREE
LinuxWorld Reader's Choice Award Winner for best database on Linux.
http://ads.osdn.com/?ad_id=5588&alloc_id=12065&op=click