This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

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

Created on 2010-05-16 19:34 by, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (2)
msg105875 - (view) Author: John W. Shipman ( 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

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
$ bad
Traceback (most recent call last):
  File "bad", line 23, in <module>
  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__":
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.
Date User Action Args
2022-04-11 14:57:01adminsetgithub: 52981
2010-08-01 06:53:49georg.brandlsetstatus: open -> closed

nosy: + georg.brandl
messages: + msg112271

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