Need to call functions/class_methods etc using string ref :How
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Mon Nov 26 14:04:40 EST 2007
Donn Ingle a écrit :
>>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!
>
> Yes, I suggested to him (by email) this:
>
> thisinstance = SomeObject.__class__.__dict__
> <Then you have a list of strings that may be function names, so:>
This will only get attributes defined in SomeObject.__class__ - not the
one defined in the parent classes. Nor methods dynamically bound to a
specific instance.
> for f in yourlist:
> if f in thisinstance: eval(f)(params)
>
> Which would vet the functions too.
You *still* don't need eval here.
target = <module or any other objet here>
for funcname in funclist:
func = getattr(target, funcname, None)
if callable(func):
func(*args, **kwargs)
I've almost never had a real use case for eval (or exec) in 7 years.
More information about the Python-list
mailing list