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.

classification
Title: optparse: Callback example 1 is confusing
Type: Stage:
Components: Documentation Versions: Python 3.0, Python 2.4, Python 3.1, Python 2.7, Python 2.6, Python 2.5
process
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: georg.brandl Nosy List: georg.brandl, jkankiewicz
Priority: normal Keywords:

Created on 2009-01-04 06:50 by jkankiewicz, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (2)
msg79039 - (view) Author: Jason Kankiewicz (jkankiewicz) Date: 2009-01-04 06:50
"Callback example 1: trivial callback" reads

    Here’s an example of a callback option that takes no arguments, and
simply records that the option was seen:

        def record_foo_seen(option, opt_str, value, parser):
            parser.saw_foo = True

        parser.add_option("--foo", action="callback",
callback=record_foo_seen)

but the following paragraph

    Of course, you could do that with the store_true action.

is wrong because

        parser.add_option("--foo", action="store_true", dest="saw_foo")

would actually be duplicated by

        def record_foo_seen(option, opt_str, value, parser):
            parser.values.saw_foo = True

        parser.add_option("--foo", action="callback",
callback=record_foo_seen)

For example:
>>> from optparse import OptionParser
>>> parser = OptionParser()
>>> def record_foo_seen(option, opt_str, value, parser):
...     parser.saw_foo = True
...
>>> parser.add_option("--foo", action="callback", callback=record_foo_seen)
<Option at 0xab4f58: --foo>
>>> parser.parse_args(['--foo'])
(<Values at 0xabb0f8: {}>, [])
>>> parser = OptionParser()
>>> parser.add_option("--foo", action="store_true", dest="saw_foo")
<Option at 0xabb1e8: --foo>
>>> parser.parse_args(['--foo'])
(<Values at 0xabb1c0: {'saw_foo': True}>, [])
>>> parser = OptionParser()
>>> def record_foo_seen(option, opt_str, value, parser):
...     parser.values.saw_foo = True
...
>>> parser.add_option("--foo", action="callback", callback=record_foo_seen)
<Option at 0xabb508: --foo>
>>> parser.parse_args(['--foo'])
(<Values at 0xabb3f0: {'saw_foo': True}>, [])
msg81206 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2009-02-05 11:33
You're right, I've fixed that in r69298.
History
Date User Action Args
2022-04-11 14:56:43adminsetgithub: 49077
2009-02-05 11:33:36georg.brandlsetstatus: open -> closed
resolution: fixed
messages: + msg81206
2009-01-04 06:50:42jkankiewiczcreate