Re: Multi-line string extension (uplocals, upglobals)

Tim Peters (tim@ksr.com)
Wed, 20 Apr 94 13:54:19 -0400

> ...
> But to do that, some way to get at the caller's local namespace is
> needed. I could construct it by hand _in_ the caller and then pass it in
> explicitly ("dir()" in a function returns a list of the func's locals'
> names, from which a dict can be built; ironically enough, the
> _implementation_ of dir() actually builds the whole dictionary, but
> throws away everything except the keys ...)

Sickness alert: since "dir()" in a function _does_ materialize a
snapshot of the locals into a dict as a side-effect, this variation
"works":

def uplevels1( ignore ):
global testlocals
import sys
try:
1 + '' # make an error happen
except: # get caller's frame
frame = sys.exc_traceback.tb_frame.f_back
testlocals = frame.f_locals # caller's locals

def test():
i, j, k = 1, 2, 3
uplevels1( dir() ) # invoking dir for its dict-building side-effect
print 'in test'
print 'locals =', testlocals

test()
print 'back from test'
print 'locals =', testlocals

I.e., that prints

in test
locals = {'j': 2, 'i': 1, 'k': 3}
back from test
locals = {'j': 2, 'i': 1, 'k': 3}

where before an empty dict was displayed from inside test.

don't-try-this-at-home-ly y'rs - tim

Tim Peters tim@ksr.com
not speaking for Kendall Square Research Corp