[Tutor] Resetting the namespace

Patrick Sabin patrick.just4fun at gmail.com
Mon Mar 8 18:15:56 CET 2010

I found this piece of code, which completely puzzles me, in the pdb 
module of the trunk:

class Pdb(bdb.Bdb, cmd.Cmd):
     def _runscript(self, filename):
         # The script has to run in __main__ namespace (or imports from
         # __main__ will break).
         # So we clear up the __main__ and set several special variables
         # (this gets rid of pdb's globals and cleans old variables on
         # restarts).
         import __main__
         __main__.__dict__.update({"__name__"    : "__main__",
                                   "__file__"    : filename,
                                   "__builtins__": __builtins__,

The intention of this code is to reset the namespace, before executing a 

When I try to do something similar, i.e. __main__.__dict__.clear(), I 
loose the __builtins__ variable in the namespace, e.g.:

 >>> import __main__
 >>> print __builtins__
<module '__builtin__' (built-in)>
 >>> __main__.__dict__.clear()
 >>> print __builtins__
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name '__builtins__' is not defined

But for some reason the code mentioned above actually works in the case 
of pdb. Any ideas why?

- Patrick

More information about the Tutor mailing list