unexpected optparse set_default/set_defaults behavior

Steven Bethard steven.bethard at gmail.com
Fri Aug 17 19:56:03 CEST 2007


mbeachy at gmail.com wrote:
> Some rather unexpected behavior in the set_default/set_defaults
> methods for OptionParser that I noticed recently:
> 
>>>> import optparse
>>>> parser = optparse.OptionParser()
>>>> parser.add_option("-r", "--restart", dest="restart", action="store_true")
> <Option at 0x-483b3414: -r/--restart>
>>>> parser.defaults
> {'restart': None}
>>>> parser.set_default("retart", False)
>>>> parser.defaults
> {'retart': False, 'restart': None}
> 
> Why does set_default not raise an exception when passed a key that it
> doesn't recognize?
> 
> Bad typysts bewaer.
> 
> The only reason I can think not to raise an exception is so that
> defaults can be defined before the options are added. Is there some
> use case that I'm not thinking of here?

I'm not really sure what other use case there is with optparse, but 
argparse has the same behavior because sometimes it's useful to store 
values that can't be changed by anything on the command line. This is 
particularly useful when you're dealing with sub-commands::

     >>> import argparse
     >>> parser = argparse.ArgumentParser()
     >>> subparsers = parser.add_subparsers()

     # set up the foo parser, adding a static "func" default
     >>> foo_parser = subparsers.add_parser('foo')
     >>> foo_parser.set_defaults(func=lambda: 'do something for foo')
     >>> foo_parser.add_argument('--foo')

     # set up the bar parser, adding a staic "func" default
     >>> bar_parser = subparsers.add_parser('bar')
     >>> bar_parser.set_defaults(func=lambda: 'do something for bar')
     >>> bar_parser.add_argument('bar')

     # parse the arguments and call whichever "func" was selected
     >>> args = parser.parse_args(['bar', '13'])
     >>> args.func()
     'do something for bar'

I know optparse doesn't support sub-commands, but I can imagine that if 
you were trying to hack optparse to do something similar you might find 
it useful to be able to specify defaults that weren't ever set by 
anything at the command line.

STeVe



More information about the Python-list mailing list