Dynamic function calling
Burkhard Kloss
bk at xk7.com
Fri Sep 1 10:22:35 EDT 2000
> 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)?
If you are in the same module as the function you can call through locals:
locals() ['test'] ()
or, breaking down the steps
mydict = locals()
myfunc = mydict ['test']
myfunc ()
If it's in another module, say, foo, you just say:
foo.__dict__ ['test'] ()
HTH,
Burkhard
More information about the Python-list
mailing list