Building a function call?

Larry Bates lbates at syscononline.com
Wed Jul 13 09:09:40 EDT 2005


Normally when I want to do what you describe I want to
do it for several functions not just a single one.
You can use a dictionary to hold the function names and
pointers to the functions themselves and then call them
by indexing into the dictionary.  This works for me:

def dothat(x,y):
    print "x=", x, " y=", y
    return

def doanother(x, y, z):
    print "x=", x, " y=", y, " z=", z
    return


xdict={'dothat': dothat,
       'doanother': doanother}

s='dothat'
t=(1,2)
xdict[s](*t)

results in:

x= 1  y= 2

s='another'
t=(1,2, 3)
xdict[s](*t)

results in:

x= 1  y= 2  z=3



Larry Bates


Francois De Serres wrote:
> Hiho,
> 
> Having a string: "dothat"
> and a tuple: (x, y)
> 1. What's the best way to build a function call like: dothat(x,y)?
> 
> Assuming dothat is def'd in the same module,
> 2. is: eval("dothat(x,y)", None, (('x', 100), ('y', 200)))
> the right way to have it executed?
> 
> If dothat is def'd in another module:
> 3. what would be the right way to initialize the globals to pass to eval ?
> 
> 
> TIA,
> Francois
> 
> 



More information about the Python-list mailing list