Dynamic function calling

Greg Landrum glandrum at my-deja.com
Fri Sep 1 10:18:00 EDT 2000


In article <39AFA5D5.399EDC41 at nokia.com>,
  Olaf Meyer <olaf.meyer at nokia.com> wrote:
> I'm wondering if it is possible to call functions just by having
access
> to their name in a string value. Something similar to:
>
>   def test():
>      print "test function"
>
>   f = "test"
>   apply(f, ())
>
> This does not work of course, because f does not have the right type.
> Is there a way to get a function object from the name (string)?
>

Yep, you want to use eval():
>>> def test():
...     print 'foo'
...
>>> f = eval('test')
>>> f()
foo



Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list