Need to call functions/class_methods etc using string ref :How

George Sakkis george.sakkis at gmail.com
Mon Nov 26 21:57:46 EST 2007


On Nov 26, 2:04 pm, Bruno Desthuilliers

<bdesth.quelquech... at free.quelquepart.fr> wrote:
> 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.

That's not to say there aren't any. In one project I'm using exec to
parse user provided function bodies from a web interface into real
python functions (the function signatures are auto generated). Of
course it's a secure environment, with trusted users, etc. Although
Python's current support for code generation (source <-> ast <->
bytecode roundtrip) is far from perfect, it's much easier and more
powerful than building from scratch a domain specific toy language,
which might well turn out to be less expressive than necessary for the
given problem domain. I guess Lisp/Scheme would be even more suited
for this task but then again there's a Web framework (TurboGears), an
ORM (SqlAlchemy) an RPC middleware (Pyro) and a dozen more batteries,
both standard and 3rd party. Can't think of anything better than
Python for this project.

George



More information about the Python-list mailing list