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

André andre.roberge at
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:


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


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.

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

exec user_code in symbols

where user_code is

interp = SingleConsole()

# InteractiveConsole is very similar to the class of the same name
# in module 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,

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

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

More information about the Python-list mailing list