Self Printing Programs in Python

This post is a few years old now, so some details (or my opinions) might be out of date.
I would still love to hear your feedback in the comments below. Enjoy!

Let’s talk about self printing programs (or, quines). A self printing program is, as is its name, self explanatory. Today I thought about how to implement a quine in Python, I whipped up a solution on my own and then posed the challenge to some people in the office. These are the results:

My Version 

s = r"print 's = r\"{0}\"'.format(s), '\n', s" 
print 's = r\"{0}\"'.format(s), '\n', s

This exemplifies a common way to implement a quine - the main problem is that you have to use some sort of function that prints. But of course, you also have to print that function, and so on. The way to deal with this is put the entire program in a string, except the assignment to that string, then print the assignment (where you can use the string itself to avoid explicitly writing it again, thus avoiding the recursion), and then the string.  Notice there’s a lot of playing with quotation marks. Next is a version that tries to solve this.

Using chr for Quotation Marks

a = "b = chr(97) + chr(32) + chr(61) + chr(32) + chr(34); b += a; print b + chr(34); print a"
b = chr(97) + chr(32) + chr(61) + chr(32) + chr(34); b += a; print b + chr(34); print a

This version (while a bit cumbersome) solves the quotation marks problem by just explicitly printing the ascii characters.

Using exec Instead of Repeating the print

s = r"print 's = r\"' + s + '\"' + '\nexec(s)'"
exec(s)

I really likes this version, as it mostly avoids repeating the code in the two lines.

The Smartass Approach

Well, the first person I introduced this challenge to, had a pretty wiseass, but overall, clever approach. He did this:

print open(__file__).read()

This works, and is pretty clever, but it obviously isn’t what quines are all about. It also wouldn’t work in an interactive shell.

The “Google” Way

After I got the above answers, I just had to google Python quines and see what comes up. A StackOverflow thread points out this (pretty cool) snippet:

_=''_=%r;print _%%_'';print _%_

It assigns to the variable _ a string which is contains the entire code, except for its own value which is replaced by a formatting instruction, and then print _ and feeds itself into its formatting. Looks obfuscated, but it’s pretty cool when you take a deeper look.

Discuss this post at the comment section below.
Follow me on Twitter , Facebook or Google+

Similar Posts