On Mon, Nov 26, 2007 at 04:07:03PM +0530, Ravi Kumar wrote regarding Need to call functions/class_methods etc using string ref :How: > > Hi, > First of all, since this is my first mail to Python-List, I want to say > "Hello world!" > After that; > I am stuck in a project. Actually I am writing a module (for testing > now), which takes URL, parses it, finds which modules and then which > method to call or which class to initiate and which string to load. > So far, I have done some basic URL manipulation and validation and > extracted the name of modules in a dict > { > 'ModuleName-1': None, > 'ModuleName-2': None > --ETC-- > } > Now I want your help about how to call the function i.e _render() in > the module. I have to iterate it calling all modules/also Class.methods > and assinging the values in dict for each key as modulename. > Means, > just take that moduleName is a string which contains the name of module > to load. > FuncName is the string which contains the name of def <function> to > call > clName is the string which contains the name of the Class, which is to > init and get returned object. > means everything in string. > ALso, if there are multiple methods to do it, if you provide a little > pros/cons and comments, it would really be very nice of you. > Before I came here, I have searched Google, and found a way > hasattr()/getattr(), but that confused me a little and didnt worked for > me. I am missing something I know, so please ENLIGHTEN Me :) > Thanks in advance EVen you read this mail :P > -- > -=Ravi=-
I see someone already showed you eval. Eval is evil. Don't use it. Especially if the functions are coming to you from a public URL! You are on the right track putting the module names in a dictionary. Now tie those dictionary keys to functions. func = { 'function_a': function_a, 'function_b': function_b } now you can call them as follows, with the desired function name extracted from the URL into the variable f_request: if f_request in func: result = func[f_request]() This way, users can't call functions you haven't explicitly added to the func dictionary. Cheers, Cliff > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list