Nanjundi a écrit : > On Apr 10, 10:23 am, "Lucas Malor" <[EMAIL PROTECTED]> wrote: >
>> 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? > > Use exec to assign to a variable. Oh, yes, soooo simple !-) > >>>> def testPrint(msg): > > ... print 'Msg: %s' % msg ... > >>>> sfunc = "testPrint" exec("f = %s" % sfunc) f('Hello Python') > > Msg: Hello Python > > & use 'f = self.%s' % name for class methods. > > Hope its not a bad practice! Using exec (or eval) is not a bad practice in itself, but using it when there are much simpler solutions is certainly a WTF. See the other posts in this thread for more idiomatic solutions to the OP's problem (mainly: dict-based dispatch, use of getattr on module objects, and use of the locals() and/or globals() builtins). HTH -- http://mail.python.org/mailman/listinfo/python-list