Have you ever tried to write a program that outputs itself when you run it? While I was eating at Wahoo’s Fish Tacos with Mike and Matt a couple of weeks ago, Matt brought up the topic. Being the guy that he is, he whipped out a napkin and proceeded to write an example of a self replicating C program.

I guess it’s been a fairly well-known topic for a while, after being popularized by Ken Thompson’s speech twenty years ago. These self-replicating programs have a special name- they’re called quines. It’s an interesting, and surprisingly difficult task to make a quine, especially in low-level languages like C. I should know, because I had to beat my head against the problem for a while before it came to me.

The interesting thing, though, is it’s not that hard to write a quine in Python. Due to some of the interesting essays by Paul Graham that I’ve been reading, I’ve started learning some Python over the last week. Despite knowing only a very small amount of the language, I was already able to write this quine tonight:

x = ['print "x =", x', 'for m in x: print m']
print "x =", x
for m in x: print m

For anyone that wants to try running that and see that it does indeed output its source, get a Python interpreter and try it out. My code above is not that impressive as quines go. I’m sure that in a powerful language like Python, somebody out there has already written a one-liner. What is impressive is that the language is powerful enough and convenient enough that writing a quine is easily doable for a complete beginner. If I were using FORTRAN, for instance, I’d have to do a fair amount of brushing up before I’d even have a hope. I’ve never been much of a fan of Java. I’ve always been a Perl guy, except for graphics engines (which I did in C). Paul Graham’s on to something with Python, though. It’s surprisingly easy to get up to speed with it, and it’s much more powerful than I expected, too.

Update: This page includes many Python quines, including one-liners and one that’s logically equivalent to mine.

Update 2: Come on all you geeks out there, post your quines as comments here! Matt, you could make one in Javascript, right? I mean… you’re not a wuss, right? Ducky, how about flexing those MATLAB trained mental muscles of yours? Mike W, you said you were getting pretty into PHP. .. post me a quine!