Reflection: Calling Methods Dynamically by Name

Remco Gerlich scarblac at pino.selwerd.nl
Thu Jan 11 15:18:39 EST 2001


D-Man <dsh8290 at rit.edu> wrote in comp.lang.python:
> On Thu, Jan 11, 2001 at 01:41:34PM +0700, Prateep Siamwalla wrote:
> | You will want to use getattr() and apply()
> 
> Is it better to use getattr() and apply() than to use exec?

Yes.

> For example,
> 
> mc = MyClass()
> funcname = "ProcessData"
> args = ("Data", 1, 3)
> exec( "mc." + funcname + "('Data' , 1 , 3 ) " )

Here, a new string is constructed, the string must be parsed (something that
usually only occurs at compile time), and then the tuple (that you just
converted to a string) must be built up from the string again.
Then it calls getattr() and apply(), basically.

And you don't get the return value of the method (although eval() would give
you that).

And if the string didn't have 'Data' but 
"Data'); import os; os.system('rm -r ~') #"
you might have yourself a security problem.

Situations where exec is the natural solution are pretty rare.

-- 
Remco Gerlich



More information about the Python-list mailing list