Clearing globals in CPython

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Oct 1 12:00:37 EDT 2014


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.

I expected that global variables would be all lost, but built-ins would
remain, since they don't live in the global namespace. I was wrong:

>>> globals().clear()
>>> x = len([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'len' is not defined

The reason, I think, is that CPython has a special __builtins__ global
variable that the interpreter uses to access built-in functions. What
*appears* to be happening is that if that __builtins__ global is missing,
CPython can not access the built-ins.

(Supporting this interpretation: IronPython, like CPython, has a
__builtins__ global, and behaves the same when the globals() are cleared.
Jython, which does not have a __builtins__ global, does not.)

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

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?


-- 
Steven




More information about the Python-list mailing list