Q: dynamic function call

Robert Roy rjroy at NO-SPAM.magma.ca
Wed Dec 20 14:34:30 EST 2000


On Wed, 20 Dec 2000 11:56:28 -0600, "Hwanjo Yu" <hwanjoyu at uiuc.edu>
wrote:

>Hi,
>
>Is there any way to bind a function name at runtime ?
>For instance, we don't know the function name to call, but we know the
>function name is saved in a variable, "fname".
>How to call it in this case ?
>Thanks in advance.
>
Functions are first-class objects in python so it is no big deal to
assign them to other names and then call them. There are also several
ways to resolve names at runtime. Here are few quick examples of how
this could be done.

Bob
#########
# this is the function we will play with
def cb(name):
    print 'callback:', name
    
# this gets passed the function
def foo(name, callback):
    callback(name)

#this gets passed the function name
def bar(name, callbackname):
    globals()[callbackname](name)

# call foo 
foo('joe',cb)

#bind cb to c and call
c=cb
c('ralph')

# use eval to run from function name
eval('cb')('called from eval')

# find the function in the locals dictionary
locals()['cb']('called from locals')

#find the function in the globals dictionary
globals()['cb']('called from globals')

# call bar
bar('cb called from globals in function', 'cb')
# note that we bound to c earlier so can call it as well
bar('c called from globals in function', 'c')






More information about the Python-list mailing list