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

Georg Brandl g.brandl at gmx.net
Fri Mar 20 20:14:43 CET 2009

Thomas Lee schrieb:
> 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]))


options_dict = vars(options)

already does what you want?  optparse seems to set nonpresent attributes
for options to None.


Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.

More information about the Python-ideas mailing list