[Python-ideas] A read-only, dict-like optparse.Value
Thomas Lee
tom at vector-seven.com
Fri Mar 20 23:21:42 CET 2009
Thanks Georg, this is pretty much exactly what I was looking for.
Somehow I had never heard of the vars builtin before!
Regards,
Tom
Georg Brandl wrote:
> 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]))
>>
>
> Perhaps
>
> options_dict = vars(options)
>
> already does what you want? optparse seems to set nonpresent attributes
> for options to None.
>
> Georg
>
>
More information about the Python-ideas
mailing list