A Shorter Quine in Python

March 20, 2010 | Computer Science | By: Mark VandeWettering

Quines are programs that when run produce themselves as output. Previously I had written a fairly longish one in Python. I was reading Russ Cox’s latest blog article (more skimming than reading actually, it’s neatly subtle) but it said something obvious that I hadn’t clicked on before: the repr function takes a value, and converts it to a string value that is its representation. Most of the difficulty in making a short quine is in picking a representation which is compact. Since repr is a builtin function, that makes it very compact. A few minutes of tinkering resulted in this two line quine:

#!/usr/bin/env python
s = '#!/usr/bin/env python\ns = %s ; print s %% repr(s)' ; print s % repr(s)

It could actually be made shorter and fit on one line, but I think most good programs should specify the interpreter they use. That necessitates a second line.

Russ goes on to do something truly remarkable: a zip or tar.gz file which when unzipped produces a new copy of itself. I am gonna ponder that a bit more and maybe work on my own version.

Comments

Comment from Bob
Time 7/20/2010 at 10:10 am

You can use the %r formatting, which essentially does an repr() style function. For instance:

r=’r=%r;print r%%r’;print r%r

Comment from Mike Perdide
Time 6/6/2011 at 6:16 am

I’m not sure I totally understand what a quine is, but I think this could be done dynamically by :

#!/usr/bin/env python
print open(__file__).read()

or with the module inspect, to display only some methods and not the whole file:

#!/usr/bin/env python
from inspect import getsource

def quine_this(function):
def wrapper(*args):
print “===== Source code:”
print getsource(function),
print “==================”
return function(*args)
return wrapper

@quine_this
def cool_method():
print “moo”

if __name__ == “__main__”:
cool_method()

Comment from Mark VandeWettering
Time 6/6/2011 at 10:26 am

This is akin to the rather trivial basic program of my youth:

100 LIST

It’s not hard to write a quine in languages which have a method of “reflection”, that can examine their own data structures during program execution. Python is a good example. It is generally considered to be “cheating” to use a program which uses an external resource (such as opening its own source file). In particular, I think it cheats you out of the opportunity of figuring out something really cool about programs and programming languages.