Building a function call?

Francois De Serres fdeserres at gmx.net
Wed Jul 13 09:15:54 EDT 2005


Peter Hansen wrote:

>Roland Heiber wrote:
>  
>
>>Not the best (not at all) but one way:
>>
>>def dothat(x,y):
>>  print "Called with:", x, y
>>
>>c = (1,2)
>>
>>locals().get("dothat")(*c)
>>    
>>
>
>As you say, not the best, but in fact not really advisable under any 
>circumstances.  locals() returns "module level" stuff only when executed 
>_at_ module level (i.e. not inside a function).  Otherwise it will 
>return only the local variables of the frame its in.
>
>Better is this, since it works for the OP's requirements in either 
>situation.
>
>   globals()['dothat'](*c)
>
>-Peter
>  
>
Actually that's part of my dilemma... I guess the function name is 
moreoften in globals().
But the parameters in the tuple are
A) formals (that was not clear in my OP, sorry),
B) once bound by another function, I they'll become part of locals().

func = "dothat"
args = (x,y)
localcontext = ()
r = None
while r is None:
    try:
        r = eval("dothat(x,y)", None, localcontext) #how do I construct 
"dothat(x,y)"?
    except NameError:
        ensure_context(x,y) #find/compute the formals, eg: localcontext 
= (('x', 100), ('y', 200))

F.
 



More information about the Python-list mailing list