[Python-ideas] A read-only, dict-like optparse.Value

Thomas Lee tom at vector-seven.com
Fri Mar 20 15:38:39 CET 2009


Hi folks,

Would anybody support the idea of read-only dict-like behaviour of 
"options" for the following code:

====

from optparse import OptionParser
parser = OptionParser()
parser.add_option("--host", dest="host" default="localhost")
parser.add_option("--port", dest="port", default=1234)
parser.add_option("--path", dest="path", default="/tmp")
options, args = parser.parse_args()

====

As it is, you have to "know" what possible attributes are present on the 
options (effectively the set of "dest" attributes) -- I often implement 
something like the following because recently I've had to use command 
line options in a bunch of format strings:

def make_options_dict(options):
    known_options = ("host", "port", "path")
    return dict(zip(known_options, [getattr(options, attr) for attr in 
known_options]))

I don't mind having to do this, but having to hard code the options in 
there feels a bit nasty. Just as useful for my particular use case (i.e 
passing the options "dict" to a format string) would be something along 
the lines of options.todict() or dict(options). Even a way to know the 
set of "dest" attributes that are defined on "options" would be cleaner. 
e.g.

options_dict = dict(zip(options.all(), [getattr(options, attr) for attr 
in options.all()]))

Where options.all() returns all the option "dest" attribute names.

Or something to that effect.

Any thoughts?

Cheers,
T



More information about the Python-ideas mailing list