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

Ravi Kumar ra21vi at gmail.com
Mon Dec 3 09:13:55 EST 2007


WOW,
Thanks a lot. I got many options to do, and play with. Each one having its
own pros and cons. But for my requirement in project, i will go with
hasattr/getattr/callable and then calling the ref method. It seems fit for
the problem.

Thanks a lot :) again.

On Dec 1, 2007 12:45 AM, Bruno Desthuilliers <
bdesth.quelquechose at free.quelquepart.fr> wrote:

> George Sakkis a écrit :
> > 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.
>
> Indeed. But most of the time, I found that Python provides a more
> appropriate solution.
>
> > 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).
>
> A problem I've never had to solve so far, so you're the expert here -
> but what about compiling the source with compile, then instanciating a
> function object from it ?
>
> (snip)
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
-=Ravi=-
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20071203/67cb044d/attachment.html>


More information about the Python-list mailing list