Self Printing Programs in Python
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:
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.
chr for Quotation Marks
This version (while a bit cumbersome) solves the quotation marks problem by just explicitly printing the ascii characters.
exec Instead of Repeating the print
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:
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:
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.
Follow me on Twitter and Facebook