where is upvar
Fredrik Lundh
effbot at telia.com
Fri Sep 22 01:06:38 EDT 2000
Darren New wrote:
> > No, by far uglier, and unpublished, i mean, it's really not pretty.
> > Does Smalltalk do something like that? Never heard of such a
> > feature.
>
> Yes. It's how the debugger works. Smalltalk stack frames are objects just
> like everything else.
So are Python stack frames, of course.
But that's an implementation detail, and you need to use
some slightly weird tricks to access them...
import sys
def egg():
# get caller's namespace
try:
raise None
except:
frame = sys.exc_traceback.tb_frame.f_back
print frame.f_globals
print frame.f_locals
frame.f_locals["a"] = 1
frame.f_locals["b"] = 2
def spam():
a = 0
c = 3
egg()
print locals()
print b # this will fail
spam()
...and even when you do know the tricks, things don't really
work as you might expect:
$ python example.py
{'spam': <function spam at 007C261C>, 'sys': <module 'sys' (built-in)>, '__doc__
': None, 'egg': <function egg at 007C25BC>, '__name__': '__main__', '__builtins_
_': <module '__builtin__' (built-in)>}
{'c': 3, 'a': 0}
{'b': 2, 'c': 3, 'a': 0}
Traceback (most recent call last):
File "q.py", line 21, in ?
spam()
File "q.py", line 19, in spam
print b
NameError: There is no variable named 'b'
(if you don't understand what's going on here, see "Code blocks,
execution frames, and namespaces" in the language reference)
</F>
More information about the Python-list
mailing list