Baby's Intro to the CPython Source Code
or: Fun in Programming Languages
PythonMost people are familiar with the most famous Python standard lib easter eggs.
Things like The Zen of Python being available by typing import this
.
Or the XKCD comic you can open by typing import antigravity
.
I had both of these told to me pretty early in my Python career.
Some are kind of hard to discover without actually inspecting the source though.
At the start of COVID I was working on a SQLAlchemy project and realized I knew precious little about how SQL databases work, so I decided to go about building my own mini SQLite. (Code if you’re interested)
Cloning and Modifying Source Code
While I was looking into how SQL stores things in pages I came across Julia Evans’ blog post about SQLite where she clones the source code, manually re-builds it, and runs it so that she can observe some internal behavior. I couldn’t believe I’d never thought to do this type of thing myself.
I cloned the cPython source and went about inserting some print statements to watch the code execute. This really helped me grasp some of the concepts I’d heard about in tours of the CPython virtual machine.
Then I realized that since I was looking at the entire CPython source code, everything in the standard lib must be in here. Here’s a other couple things I found.
My Own Easter Egg Hunt
The first thing I thought to go looking for was the code for The Zen of Python. Since it’s part of the standard library, the code for import this
must be there somewhere so I went looking for it.
I searched the first line of the poem: “Beautiful is better than ugly”, but all that turned up was some test files and a docstring for difflib
.
Then I realized, because of Python’s import mechanism, it would have to be in a file called this.py
so I searched for that and there it was! It’s almost like they were deliberately trying to avoid people doing what I had done on my first try.
The goobers decided to use a rot13 cypher. Rude.
Antigravity
After finding the code for the above, my second thought was to go look at the Antigravity module. Since just importing it opens your default web browser I figured it must be just a script that uses webbrowser.open()
and that is indeed part of what it does, but there’s one more thing that you’d probably never know was there unless you either looked at the source or imported it and did
which, if you look carefully, shows that antigravity imports webbrowser (for opening the comic) and also hashlib and geohash.
Except…
Either way you’d end up looking at antigravity.py
and realize that the module contains one function: geohash
which implements the geohash algorithm contained in xkcd.com/426/.
I kind of love the mutual love between Randall Munroe and the Python community.
Having fun things like this in Python’s standard lib is one of my favorite reasons to recommend it to newcomers to programming.
I like using a language for my job that people have spent time making enjoyable.