Dynamic function calling

Alex Martelli aleaxit at yahoo.com
Fri Sep 1 16:10:11 CEST 2000


"Olaf Meyer" <olaf.meyer at nokia.com> wrote in message
news:39AFA5D5.399EDC41 at nokia.com...
> 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)?

Isn't this essentially the same function as just posed by "Igor V.
Rafienko" <igorr at ifi.uio.no> ...?

Anyway: the name string by itself does not univocally identify the
function object to be used, but it becomes sufficient if you also
know where to look it up.

Consider, specifically:

def docall(kind, name, dict, *args):
    funobj=dict[name]
    print "Calling",kind,
    return apply(funobj, args)

def foo():
    print 'external foo'

def bar():
    def foo():
        print 'internal foo'
    docall('local','foo',vars())
    docall('global','foo',globals())

Importing this and calling bar() will give us...:

Calling local internal foo
Calling global external foo


Alex






More information about the Python-list mailing list