Clearing globals in CPython

Terry Reedy tjreedy at udel.edu
Wed Oct 1 20:44:26 CEST 2014


On 10/1/2014 12:00 PM, Steven D'Aprano wrote:
> Out of curiosity, I ran:
>
> globals().clear()
>
> in the interactive interpreter. It broke much more than I expected!
> Built-ins were no longer available, and import stopped working.

As you discovered, this reduces the interpreter to a pure syntax machine 
with no name bindings -- sort of like a high-level assembler with no 
access to a function library.

> I expected that global variables would be all lost, but built-ins would
> remain, since they don't live in the global namespace. ...
> The reason, I think, is that CPython has a special __builtins__ global
> variable that the interpreter uses to access built-in functions.

When executing statements from Shell, Idle restores __builtins__.
 >>> globals().clear()
 >>> print(dir())
['__builtins__']
 >>> print(__builtins__)
<long listing>

The odd thing is that executing the same code from a file prints [] and 
then raises "NameError: name '__builtins__' is not defined".

> Well that's okay, I thought to myself, I'll just import the built-in
> functions:
>
>>>> from builtins import len  # use '__builtin__' in Python 2
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> ImportError: __import__ not found

Most keyword statements are implemented by internal functions not 
accessible from Python except through the statement syntax.  Import is 
an exception.  This is one of the hooks that allow the behavior of 
imports to be modified.  The result is like, for instance, programming 
in C with 'include' disabled.

> Oops.
>
> So, with no built-ins available, import no longer works. That makes things
> rather tricky.
>
> Obviously the easiest way to recover is to exit the current session and
> restart it, but as a challenge, can we recover from this state?


-- 
Terry Jan Reedy




More information about the Python-list mailing list