Hard to understand 'eval'

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Mon Jun 16 11:18:53 CEST 2008


TheSaint a écrit :
> On 01:15, lunedì 16 giugno 2008 Calvin Spealman wrote:
> 
>> such as getattr(obj,
>> methname)(a, b, c). Does this make sense?
> 
> This is big enlightenment :) Thank you! :)
> 
> I found problem with eval() when it comes to pass quoted strings.
> I circumvent that by encapsulating the strings in variable or tuple.
> The principle is to have a name which will refers a function somewhere in the
> program and to call that function, plus additional data passed in.
> 
> In other word I'd expect something:
> 
> function_list= ['add' ,'paint', 'read']
> for func in function_list:
>       func(*data)

Can't work - function_list is a list of strings, not a list of 
functions. If the functions you intend to call are already bound to 
names in the current scope, you don't even need any extra lookup 
indirection:

def add(*args):
   # code here

from some_module import paint

obj = SomeClass()
read = obj.read

functions = [add, paint, read]
args = [1, 2]
for func in functions:
     func(*args)


> I tried getattr,

getattr is useful when you only have the name of the 
function/method/whatever attribute as a string. And a target object 
(hint: modules are objects too) of course - if the name lives either in 
the global or local namespace, you can access it by name using the dicts 
returned by resp. the globals() and locals() functions.

HTH



More information about the Python-list mailing list