Anonymus functions revisited

Kay Schluehr kay.schluehr at gmx.net
Wed Mar 23 15:31:38 CET 2005


Ron wrote:

> On 23 Mar 2005 10:13:16 GMT, Duncan Booth
> <duncan.booth at invalid.invalid> wrote:
>
>
>> Do I really need to mention that the whole concept here is broken.
This
>> only works if you call it from global scope. If you call it from
inside a
>> function it [usually] won't work:
>>
>
>
> That's only becuase it was asked to go up 1 frame, and not 2.
>
> def makeVars(**nameVals):
>    sys._getframe(2).f_locals.update(nameVals) # <- get 2 frames up.
>
>    def test():
>    try: b
>    except NameError: print "Before makeVars: NameError"
>    else: print "Before makeVars: Not NameError"
>    makeVars(b=2)
>    try: b
>    except NameError: print "After makeVars: NameError"
>    else: print "After makeVars: Not NameError"
>
>
> import sys
> test()
>
>
> Before makeVars: NameError
> After makeVars: Not NameError
>
>

That's true only because the globals are updated by {"b":2}
two levels down.

If You nest the test() function You reproduce the error again:

def test():
   def inner():          try: b
       except NameError: print "Before makeVars: NameError"
       else: print "Before makeVars: Not NameError"
       makeVars(b=2)
       try: b
       except NameError: print "After makeVars: NameError"
       else: print "After makeVars: Not NameError"
   inner()


Before makeVars: NameError
After makeVars: NameError


A working makeVars seems not to be different from

def makeVars(**nameVals):
   globals().update(nameVals)


Regards Kay




More information about the Python-list mailing list