calling a method using a variable name?

Alan McIntyre fusion at
Fri Mar 14 23:15:01 CET 2003

Ah, thanks Jeremy.  I hadn't thoroughly read up on exec; here's an 
excerpt from the Python Essential Reference:

"When a string is passed to exec, eval() or execfile(), the parser first 
compiles it into bytecode.  Because this process is expensive, it may be 
better to precompile the code and reuse the bytecode on subsequent calls 
if the code is going to be executed multiple times."

Or just use getattr to get to the method in this case, as you pointed 
out. :)  Building the call string and running exec 100k times takes 15.8 
seconds on my machine, whereas using getattr and then calling the method 
returned takes .34 sec for 100k repetitions.


Jeremy Hylton wrote:
> Actually, you should use getattr() instead of exec.
> def callMethod(obj, methname, *args, **kwargs):
>     meth = getattr(obj, methname)
>     return meth(*args, **kwargs)

More information about the Python-list mailing list