scope hacks
Andy Freeman
anamax at earthlink.net
Wed Jun 21 01:37:05 EDT 2000
I like local functions that can be recursive AND have access
to the enclosing function's state. I tried to use locals()
in the following way and ran into a bug; is it me or Python 1.5?
With the tagged line, everything works as expected. Without
the tagged line, inner's second print is {'j' : <value>};
it doesn't include inner's definition. (It behaves like a
bogus optimization, namely, not adding local fns to the local
scope unless there's some "not call" reference or an explicit
locals(), the bogosity being that the default for v is an
explicit use of locals().)
def outer(j):
def inner(i, v = locals()): # v should get outer's locals()
print "inner: " + str(i)
print v
if i:
return i + v['inner'](i-1)
else:
return 1
locals() # why is this line necessary?
print "outer"
inner(j)
thanks,
-andy
Sent via Deja.com http://www.deja.com/
Before you buy.
More information about the Python-list
mailing list