Quine (Python)

From LiteratePrograms

Jump to: navigation, search
Other implementations: BASIC | Clojure | dc | Erlang | Forth | JavaScript / URI | Lisp | Oz | Perl | Python | Smalltalk

A "Quine" is a program that prints its own sourcecode when it is run. For a definition, see Wikipedia's article on Quines. I also recommend David Madore's Page for a highly readable introduction.

In Python, we can use the '%r' string formatting feature to create a highly readable Quine:

<<Quine1.py>>=
quine = 'quine = %r\r\nprint quine %% quine'
print quine % quine

"%r" formats a string (or, in fact, many objects) the way "it would be written in sourcecode", so it essentially does all the work. If we didn't care for readability, we could make a one-liner of this:

<<Quine2.py>>=
_='_=%r;print _%%_';print _%_

However, I guess using "%r" may be considered "cheating" by Quine-purists, so here's an alternative version without using string formating instructions:

<<Quine3.py>>=
def quine(source):
    quote = '"'*3
    print source + '(' + quote + source + quote + ')'
quine("""def quine(source):
    quote = '"'*3
    print source + '(' + quote + source + quote + ')'
quine""")

This actually comes closest to David Madore's “quine ‘quine’”.

Another way of implementing quines is to have them print the contents of their own files. This is made possible by the fact that Python is an interpreted language; in C, such a quine would be impossible, due to the difference between source code and executable file. This example makes use of the __file__ variable which is defined whenever a Python script is run:

<<Quine4.py>>=
import sys
fp = open(__file__)
sys.stdout.write(fp.read())
fp.close()

On UNIX systems, it tends not to be a requirement to close file handles when they are opened in read ('r') mode. Also, sys.stdout.write is used in the following example because the print statement also adds a trailing newline, which is not part of the source code. However, 'print x,' omits the trailing newline, therefore the previous example may be written in one line (28 characters in total):

<<Quine5.py>>=
print open(__file__).read(),

Of course, this may be classified by some as cheating, as we are exploiting the interpreted nature of Python.

Here are some more examples of Quines in Python:

a=('%s"a=(%%r,%%r)"%%a;%s"exec(a[0]%%(a[1],a[1]))"','print ')
exec(a[0]%(a[1],a[1]))


a,b='%s"a,b=%%r,%%r"%%(a,b);%s"exec(a%%(b,b))"','print '
exec(a%(b,b))


a='%s "a=%%r"%%a;%s "b=%%r"%%b;%s "exec(a%%(b,b,b))"'
b='print'
exec(a%(b,b,b))


a= 'print "a=",repr(a);print "exec(a)"'
exec(a)


a= 'print "a=%r"%a;print "exec(a)"'
exec(a)


print (lambda x,y: (x*2)[:-1]+y+x[-1]*2+x[15:16]+repr(y)+x[23:24])('print (lambda x,y: (x*2)[:-1]+y+x[-1]*2+x[15:16]+repr(y)+x[23:24])(\'','\\')


print (lambda x: x+")("+repr(x)+")")('print (lambda x: x+")("+repr(x)+")"')


print (lambda x:x+repr((x,)))('print (lambda x:x+repr((x,)))',)


a='print "a=%r;exec(a)"%a';exec(a)

The following is a Quine based on Ken Thompson's Turing Award lecture on trusting trust.

source_code = [112, 114, 105, 110, 116, 32, 34, 115, 111, 117, 114, 99, 101, 95, 99, 111, 100, 101, 32, 61, 32, 34, 32, 43, 32, 115, 116, 114, 40, 115, 111, 117, 114, 99, 101, 95, 99, 111, 100, 101, 41, 10, 112, 114, 105, 110, 116, 32, 39, 39, 46, 106, 111, 105, 110, 40, 91, 99, 104, 114, 40, 120, 41, 32, 102, 111, 114, 32, 120, 32, 105, 110, 32, 115, 111, 117, 114, 99, 101, 95, 99, 111, 100, 101, 93, 41, 44, 10]
print "source_code = " + str(source_code)
print ''.join([chr(x) for x in source_code]),

The key here was to store the second line of the program onwards as an array of ASCII codes. This is best done when the quine is programatically generated. As such, it is created with the following code:

# Quine Maker based on Ken Thompson's article on trusting trust
source = """print "source_code = " + str(source_code)\n\
print ''.join([chr(x) for x in source_code]),
"""
print "source_code = " + str([ord(x) for x in source])
print source,
Download code
Views