Reflection: Calling Methods Dynamically by Name

Mike Fletcher mfletch at tpresence.com
Thu Jan 11 11:53:27 EST 2001


Short answer: Yes.

Long answer: Yes :o) .  exec is an extremely heavyweight call, you're
effectively creating a new interpreter context and asking it to parse your
arbitrary code.  The getattr and apply calls are trivial in comparison, a
few name lookups.

And that's before you get into the "never use exec because it is the spawn
of the devil" philosophy that I'm sure someone will spout at you...
Mike

-----Original Message-----
From: D-Man
To: python-list at python.org
Sent: 1/11/2001 7:51 AM
Subject: Re: Reflection: Calling Methods Dynamically by Name

On Thu, Jan 11, 2001 at 01:41:34PM +0700, Prateep Siamwalla wrote:
| Chad,
| 
| You will want to use getattr() and apply()
| 

Is it better to use getattr() and apply() than to use exec?

For example,

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

-D


-- 
http://www.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list