Dynamic function calling

Michal Wallace sabren at manifestation.com
Fri Sep 1 11:45:08 EDT 2000


On Fri, 1 Sep 2000, Olaf Meyer 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)?

Yessiree:


>>> def test():
...     print "test function"
...
>>> f="test"
>>> obj = getattr(__main__, f)
>>> obj
<function test at a5560>



you can also try:



>>> exec("apply(%s, ())" % f)
test function
>>>


Cheers,

- Michal
------------------------------------------------------------------------
www.manifestation.com  www.sabren.com  www.linkwatcher.com  www.zike.net
------------------------------------------------------------------------





More information about the Python-list mailing list