Issue 8735: optparse: parse_args(values=...) does not set up default values (original) (raw)

optparse's .parse_args() method has a 'values=...' keyword argument that is documented as:

'object to store option arguments in (default: a new instance of
optparse.Values)'

There is no description of what types this argument may have. I was writing a class to digest the command line, and my bright idea was to request that .parse_args deposit the attribute values right into 'self' in the class constructor.

This works only for arguments that were actually specified; it stores no attribute value at all for missing options that have associated default options.

Below is a small script that demonstrates this behavior. It accepts one '-t' option, with default value 'DEFAULT'. Here is the output when the option is specified, and when it is not:

$ bad -t foo foo $ bad Traceback (most recent call last): File "bad", line 23, in main() File "bad", line 13, in main print args.test AttributeError: Args instance has no attribute 'test'

Here is the test script:

#!/usr/bin/env python #================================================================

bad: Demonstrate defect in optparse.

I want optparse to honor the .parse_args(values=...)

argument to store the attributes directly in self in the

constructor. It works only for options actually specified;

default values are not copied into self.

#---------------------------------------------------------------- import sys, optparse

def main(): args = Args() print args.test

class Args: def init(self): parser = optparse.OptionParser() parser.add_option ( "-t", "--test", dest="test", type="string", default="DEFAULT" ) discard, positionals = parser.parse_args(values=self)

if name == "main": main()