Q: Caller's frame, was: Re: Q: Interactive input

KevinL darius at bofh.net.au
Tue Nov 7 06:15:47 EST 2000


>>> Jan Kybic wrote
> OK, thanks. But how do I make a function out of it? Imagine I want to
> replace the five lines above with a call to one function, keyboard().
> In this function, how do I retrieve the caller's frame, to pass it to
> exec, so that it has access to the variables at the level where
> keyboard() was called from? I looked in the documentation and could
> not find anything, so I would be grateful for any pointers. 

Two options:

1) mxTools - this is probably the simplest for your requirement, although it 
may look a bit strange.  mxTools provides a 'sys.cur_frame()' method, which 
takes an argument to indicate the number of frames to rise - so 
sys.cur_frame(1) will return the frame above you.  The namespace you're after 
is in sys.cur_frame(1).f_locals and f_globals. 

2) Stackless.  Stackless python will give you this sort of behaviour, although 
I'm still wrapping my head around the intricacies of how to do that.  I'm 
reasonably sure you could do funkier things with stackless, but it may be a 
bit overblown.

mxTools will require a new module installed alongside your existing python - 
available at http://starship.python.net/crew/lemburg/mxTools.html

Stackless will require a patch to your existing python, or a whole new python 
interpreter.  It's available at http://www.stackless.com/ - and a recent (very 
good, BTW) introduction to stackless can be found at
http://www.mcmillan-inc.com/stackless.html

Note, if you're executing arbitrary code in that namespace, be careful you 
trust who it's coming from - there's a lot of potential for abuse, 
particularly around chaining through various namespaces to get up high enough 
to execute sys.*-type methods.  Filtering input to stop those sorts of games 
is, um, non-trivial ;)

KevinL





More information about the Python-list mailing list