New submission from John W. Shipman <j...@nmt.edu>:

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()
--------------------------------------------------------------

----------
components: Library (Lib)
messages: 105875
nosy: j...@nmt.edu
priority: normal
severity: normal
status: open
title: optparse: parse_args(values=...) does not set up default values
type: behavior
versions: Python 2.6

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue8735>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to