classification
Title: optparse: parse_args(values=...) does not set up default values
Type: behavior Stage:
Components: Library (Lib) Versions: Python 2.6
process
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: Nosy List: georg.brandl, john@nmt.edu
Priority: normal Keywords:

Created on 2010-05-16 19:34 by john@nmt.edu, last changed 2010-08-01 06:53 by georg.brandl. This issue is now closed.

Messages (2)
msg105875 - (view) Author: John W. Shipman (john@nmt.edu) Date: 2010-05-16 19:34
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 <module>
    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()
--------------------------------------------------------------
msg112271 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2010-08-01 06:53
Thanks for the report, I added a note in the docs in r83387.
History
Date User Action Args
2010-08-01 06:53:49georg.brandlsetstatus: open -> closed

nosy: + georg.brandl
messages: + msg112271

resolution: fixed
2010-05-16 19:34:54john@nmt.educreate