An Unreachable Hidden XKCD Easter Egg inside CPython
No, I'm not talking about import antigravity
Are you an xkcd fan? I certainly am, and it looks like the CPython developers are huge fans too, which is why the CPython code base has not one but two hidden Easter eggs related to xkcd comics.
One of the Easter eggs is not that hidden; it’s the famous import antigravity comic. However, I stumbled upon another Easter egg, which is probably not known to people outside of the CPython developer community. I shared it on my social media, and it went quite viral, so I thought I would share it with you as well.
I usually consider your inbox space very sacred and send out emails only when I have something very informative to share but as I’m preparing for the live session this weekend, I thought I will share this small piece of nerdy humor with you.
The Unreachable Code
The issue 2200 of xkcd was a humorous play on unreachable state in code and how sometimes we are not sure whether it is truly ever going to happen or not. The title of the image is also quite apt:
“ERROR: We've reached an unreachable state. Anything is possible. The limits were in our heads all along. Follow your dreams.“
Naturally, CPython has a few places in its code where the control will never reach. Typically, these parts are marked explicitly using a macro called Py_UNREACHABLE
to help the compiler perform better optimizations (see the CPython C-API documentation about it)
However, in debug builds, it is helpful to print some kind of an error message to inform developers that control reached a part of the code it should never reach. So, the CPython developers decided to bring some humor into the codebase and used the error message from this xkcd comic. See the debug build definition of this macro:
There are two versions of it. The first one, which contains the complete text from the comic, is only defined when the build option RANDALL_WAS_HERE
is defined, and Randall is, of course, the creator of xkcd. The other definition uses the title text of that comic. You can find this macro defined in the file Include/pymacro.h.
To give full closure and to end this post, how is this macro defined in the case of a release build? Usually, the macro expands into a call to the compiler built-in called __builtin_unreachable
. It informs the compiler that the control will never reach this part of the code, so it is free to perform any optimizations. This Stack Overflow answer provides a very detailed explanation of what this built-in does.
See You Later!
This is it. We are meeting for our next live session this weekend, where I’m planning to live code a small compiler and interpreter for a very limited subset of Python syntax. The goal is to provide insight into how languages like Python are implemented and work internally. Registration details are in the link below.