Re: [PATCH] %default keyword expansion
Greg Ward <[email protected]> Sun, 16 May 2004 21:18:42 -0400
| Newsgroups | gmane.comp.python.optik.user |
|---|---|
| Message-ID | <[email protected]> |
On 23 March 2004, John Belmonte said:
> Please consider the attached Optik patch, which expands occurrences of
> "%default" in a help string with the option's default value.
I've been reconsidering this patch a bit. It's not as simple as it
looks, because Optik supports a couple of different ways to specify
default option values. (Sigh: there should have been only one way to do
it.) Your example case was this:
> class MyOptionParser(OptionParser):
> def __init__(self):
> OptionParser.__init__(self, usage='usage: %prog [options]')
> self.add_option(
> '--max-foo',
> type='int',
> default=10,
> help='maximum allowable foo [default: %default]')
which is fine on its own. But if I choose one of the other ways to set
the default value for this option, namely
parser.add_option('--max-foo',
type='int',
help='maximum allowable foo [default: %default]')
parser.set_defaults(max_foo=10)
then it doesn't work. (parser.set_default('max_foo', 10) is the other
way, and it's basically the same as set_defaults() -- it's just not as
convenient, so I never use it.)
It doesn't work because your patch merely looks at option.default, and
that attribute isn't set in this case, because parser.set_defaults()
circumvents the Option instance's 'default' attribute. And as it turns
out, the parser's 'defaults' dict is the canonical source of default
values, so it must be consulted when generating help that includes
default value.
OK, no problem -- that just means the HelpFormatter needs access to the
OptionParser's default value dict. But I can't just go changing the
HelpFormatter constructor signature, since that might break backwards
compatibility for people doing custom help formatting.
Hmmm... all right, I think I know how to do it:
* add 'parser' attribute to HelpFormatter with set_parser() method
* make OptionParser constructor call formatter.set_parser(self),
so no external code has to change (NB. this ties each HelpFormatter
instance to a single OptionParser instance, so that must
be documented)
* modify the %default expansion code in HelpFormatter to look in
self.parser.defaults
OK, that sounds reasonable. I should be able to cook up a patch
tonight, maybe even check it in if I'm happy. Would be good if a few
other people could give it a test.
Greg
--
Greg Ward <[email protected]> http://www.gerg.ca/
Laziness, Impatience, Hubris.
-------------------------------------------------------
This SF.Net email is sponsored by: SourceForge.net Broadband
Sign-up now for SourceForge Broadband and get the fastest
6.0/768 connection for only $19.95/mo for the first 3 months!
http://ads.osdn.com/?ad_id=2562&alloc_id=6184&op=click