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

R. David Murray rdmurray at bitdance.com
Fri Mar 20 17:55:04 CET 2009

Thomas Lee <tom at vector-seven.com> wrote:
> 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()
> ====

I presume you know that dest is redundant there?  I ask because you
wanted to avoid retyping the option names later :)

> 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.

Well, given the implementation of optparse, you could do:


But exposing the full dictionary interface on options strikes me as a
reasonable idea.  I don't see any particular reason to make it read-only,

(NB: The Values class has some...interesting...methods that I wasn't
aware of that look somewhat intriguing.  And they aren't read-only.)

> 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?

I don't see any reason not to just duck type the options object as
dictionary-like and use the normal dictionary method names to access
the information you want.  Off the cuff it seems like a good idea
to expose an interface to this information.

Hmm.  Then I could do globals().update(options.items()), which
would simplify some of my code :)  (Whether or not that is a good
idea is a different question!)

R. David Murray           http://www.bitdance.com

More information about the Python-ideas mailing list