Problem with getting an option value

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Apr 10 15:48:50 EDT 2007


En Tue, 10 Apr 2007 11:23:37 -0300, Lucas Malor <80xuuxk02 at sneakemail.com>  
escribió:

> Peter Otten wrote:
>> Lucas Malor wrote:
>>>
>>> The problem is options is an instance, so options."delete", for  
>>> example,
>>> is wrong; I should pass options.delete . How can I do?
>>
>> Use getattr():
>
> Thank you. Do you know also if I can do a similar operation with  
> functions? I want to select with a string a certain get() function of  
> ConfigParser:
>
> if   type == "int" :
>     funcname = "getint"
> elif type == "bool" :
>     funcname = "getboolean"
> etc.
>
> How can I invoke the funcion with its name in a string?

Methods are searched the same way as "data" attributes, so you can apply  
the same technique. A first try would be (assuming cfg is a ConfigParser  
instance):

if   datatype == "int":
      funcname = "getint"
elif datatype == "bool":
      funcname = "getboolean"
func = getattr(cfg, funcname)
value = func(section, option)

(Using "type" as variable name is not a good idea - you are hiding the  
builtin "type".)
You can even write it as:

if   datatype == "int":
      func = cfg.getint
elif datatype == "bool":
      func = cfg.getboolean
value = func(section, option)

cfg.getint, by example, is a reference to the getint method of  
ConfigParser - bound to the cfg instance, and ready to be used as any  
other function. It's the same as getattr(cfg, "getint")

> PS: your answers had not arrived to my mail account. Is because I'm  
> using a disposal address? Or simply it's because I'm not registered to  
> the list?

I cannot tell for P. Otten, but many people (almost all, perhaps...)  
respond only to the list, so you may want to subscribe to it, or  
periodically check the last messages in some way. The list is mirrored  
back and forth with a newsgroup, and you can read it thru a web interfase  
(Google groups or gmane.org, by example).
Anyway, I've noticed some problems with the posted messages; I'm using  
gmane news and some messages come out of order, or very delayed, or never  
at all (I've seen replies to messages, and not the original ones).

-- 
Gabriel Genellina




More information about the Python-list mailing list