Anonymus functions revisited

Ron radam2 at tampabay.rr.com
Wed Mar 23 17:41:38 EST 2005


On 23 Mar 2005 14:47:30 GMT, Duncan Booth
<duncan.booth at invalid.invalid> wrote:

>Kay Schluehr wrote:
>
>> A working makeVars seems not to be different from
>> 
>> def makeVars(**nameVals):
>>    globals().update(nameVals)
>
>Not quite. If Ron can come up with a working makeVars it would update the 
>caller's globals whereas what you just posted updates makeVar's globals so 
>there is a difference (when the makeVars and the calling function are in 
>different modules), just not a very useful one.

How about this one?   The only reliable way I found to do it is to
pass locals() to the function.

def defvalue(**args):
    args = args.items()
    a1 = args[0]
    a2 = args[1]
    if type(a1[1]) == type({}):
        vv, names = a2, a1[1]
    else:
        vv, names = a1, a2[1]
    if names.has_key(vv[0]):
        return names[vv[0]]
    return vv[1]

f = defvalue(f=1, v=locals())  
print f           # 0

g = 19
g = defvalue(g=2, v=locals())
print g           # 19

z = 6
def f1():
    #z = 4
    z = defvalue(z=3, v=locals())
    print z
f1()




More information about the Python-list mailing list