Is access to locals() of "parent" namespace possible?

André andre.roberge at gmail.com
Fri Jul 27 22:46:20 CEST 2007


I want to give a user the possibility of "restarting" an interactive
session, by removing all the objects defined by her since the
beginning.  The way I make this possible is by having a "function"
that can be called during the interactive session using locals() as an
argument, as follows:

restart(locals())

It works.  However, I would like to make this "friendlier", i.e.
requiring the user to simply type

restart()

and have the code extract out the value of locals() of the "parent"
namespace.  I thought it might be possible using sys._getframe, but I
have not been able to figure out why.

Any help would be appreciated.
André
==================

The code below defines the class I used.  The interpreter is started
via

#--
exec user_code in symbols
#--

where user_code is

#--
interp = SingleConsole()
interp.interact()
#--


# InteractiveConsole is very similar to the class of the same name
# in module code.py of the standard library

class SingleConsole(InteractiveConsole):
    '''SingleConsole are isolated one from another'''
    def __init__(self, locals={}, filename="Isolated console"):
        self.locals = locals
        self.locals['restart'] = self.restart
        InteractiveConsole.__init__(self, self.locals,
filename=filename)

    def restart(self, loc):
        """Call this function as follows: restart(locals())

           Used to restart an interpreter session, removing all
variables
           and functions introduced by the user, but leaving Crunchy
specific
           ones in."""
        to_delete = set()
        # We can't iterate over a dict while changing its size; we do
it
        # in two steps; first identify the objects to be deleted while
        # iterating over the dict; then iterate over a set while
removing
        # the objects in the dict.
        for x in loc:
            if x not in ['__builtins__', 'crunchy', 'restart']:
                to_delete.add(x)
        for x in to_delete:
            del loc[x]
        return




More information about the Python-list mailing list