TL;DR
A self-reproducing program, usually called a quine, is a program that prints its own source code and does nothing else. The trick is that the program holds a copy of its own text as data, and it also holds the code that prints that data, with the data inserted into the right place. Quines are a simple demonstration that a program can refer to itself, and the same idea underlies results in computability theory.
Where you'll see it: programming puzzles and language tests, compiler and interpreter test suites that check output exactly, and the self-reference argument behind Gödel's incompleteness theorems and Kleene's recursion theorem.
Intuition
Writing a letter that contains its own template
Imagine a letter that says: "Copy the text between the lines below, and print it twice, once as is and once inside quotation marks, with the quotation marks and the line breaks added." Written out, the letter contains a template and the instructions for filling it. Where the instructions say "copy the text," they refer to the template, and the template contains the instructions. The letter reproduces itself because the description is complete enough to rebuild it.
A quine works the same way. It has two parts: a template, which is a string holding most of the program, and a line that prints the template with itself inserted into the right slot. The template is data, and the printing code treats it as data. That separation is the entire idea.
Why it is not obvious
A naive attempt fails. A program that contains the text print("print ...") has to contain its own text somewhere, and the copy inside the string does not automatically contain the closing quote and the rest of the line. The quine must produce the full text, including the parts that describe how to produce it. The solution is to make the string and the printing code consistent, so the copy is exact.
The math
A quine is a program whose output equals its own source text. Write for that text, and write for the output of running with no input. A quine satisfies
The construction needs a function that turns a string into a quoted, escaped version of itself. Call it . In Python this is repr, and it is what makes the template insert correctly into itself. The general recipe is:
- Write a template that contains a placeholder for the quoted form of the template.
- Build the full program as with the placeholder filled by , plus the print statement.
- Show that running the program prints exactly that text.
Step 3 is the check that makes the construction work. The output must be character-for-character identical to the source, which means the quoting function has to produce a string that reads back as the original.
The recursion theorem
Stephen Kleene's recursion theorem, from 1938, states the general principle. For any computable transformation that turns programs into programs, there is a program such that , where is the function computed by the program with index . In words, a program can be given access to its own description. A quine is the special case where returns a program that prints its input, so the program's output is its own description. The theorem is why quines exist in every sufficiently expressive language.
Worked examples
Here is a quine in Python. The first line is a string template, and the second line prints the template formatted with itself.
s = 's = %r\nprint(s %% s)'
print(s % s)Walk through it step by step.
- The variable
sholds the strings = %rfollowed by a newline andprint(s %% s). The%%is an escaped percent sign, so after formatting it becomes a single%. - The expression
s % sformats the string. The%rplaceholder is replaced byrepr(s), which issquoted with its newline written as\n. - The first line of output is therefore
s =followed by the quoted template, which is exactly the first line of the source. - The second line of output is
print(s % s), which is exactly the second line of the source, after the%%has become%. - The output is the two lines of the source, character for character.
Running this file and comparing the output with the source shows no difference. That comparison is the real test: a quine that differs from its source by one space is not a quine.
Interpretation: the program does not need to read its own file. It only needs a template and a quoting function, because the template contains enough information to recreate the text around it.
Consider a broken attempt with the same structure but without repr.
- Let the program be
s = 's = "%s"\nprint(s %% s)'on the first line andprint(s % s)on the second. The only change is that%rbecame"%s". - Format it with
s % s. The%sinserts the raw string, with no quotes added and no escapes applied, so the inserted copy contains a real line break where the source has the two characters\n, and it still contains%%. - The first line of output is
s = "s = "%s", which is not the first line of the source,s = 's = "%s"\nprint(s %% s)'. The quotes are the wrong kind and the string is cut off at a line break. - The remaining output is
print(s %% s)"followed byprint(s % s), so the output is neither the source nor valid code.
Interpretation: the program is not a quine because the copy is not faithful. Using repr, which adds quotes and escapes special characters, guarantees that the inserted copy reads back as the original string. This is the same discipline as escaping in any program that writes code, and it is why the construction depends on the quoting function, not on the template alone.
Tradeoffs and failure modes
Quines are a useful puzzle and a good test of a language's string handling, but they are rarely useful in production code.
| Situation | What goes wrong | Better choice |
|---|---|---|
| You need a program's own source for logging or versioning | A quine is brittle, and any edit changes the template and breaks the copy | Embed a version constant, or read the file from disk |
| A language's quoting differs from the one assumed | The output has the right content but the wrong escapes, so the check fails | Use the language's own quoting function such as repr, and test the output |
| Whitespace or newline handling varies | The output differs from the source by a trailing newline | Compare the output with the file in bytes, not visually |
| A compiler test requires exact output | A quine that prints even one extra character fails | Keep the program as small as possible and test it against its own file |
Quines are fragile in one specific way. Any change to the program changes the template, so the template must be updated in lockstep with the code. Writing a larger quine by hand is error-prone, and this is why most real examples are short or generated by tools.
History
The name honours the philosopher and logician Willard Van Orman Quine, who studied self-reference and indirect quotation. Douglas Hofstadter coined "quine" for such programs in his 1979 book Gödel, Escher, Bach, and the word has stuck.
The mathematics behind quines predates computers. Kleene's recursion theorem, from 1938, was an early general result showing that a program can refer to its own description. Self-reference also drives Gödel's incompleteness theorems, published in 1931. Quines became a familiar programming exercise as languages with convenient string handling spread, and they remain a standard test of a language's quoting rules.
Check yourself
QuestionIn one sentence, what must a quine's output equal?Show answer
The source text of the quine itself, character for character. Any difference, even a trailing space or a missing newline, means the program is not a quine.
QuestionWhy does the two-line Python quine use s % s rather than just printing s?Show answer
Printing s alone would output the template with the placeholder still unfilled and the escaped percent signs still doubled. The formatting step inserts the quoted template into the %r slot and turns %% into %, so the result is the full source, not just the template.
QuestionA quine's template contains a double quote character, and the template is inserted with %s instead of %r. What goes wrong?Show answer
The raw insertion puts a bare double quote into the output, which can close the surrounding string literal early. The first line of output then differs from the source, or is no longer valid code. Using %r, which quotes and escapes the string, keeps the inserted copy faithful.
QuestionA program that opens its own source file and prints it also has output equal to its source. Is it a quine?Show answer
Under the definition it meets, yes, but it is usually considered a trivial one. It depends on the file system and on the file staying unchanged. The construction the term usually names reproduces the text from a template inside the program itself, with no file access.
QuestionGive one reason a quine is useful outside a puzzle, and one reason it is a poor design for production code.Show answer
It is useful as a test of a language's string quoting and output rules, and as a demonstration of the recursion theorem. It is a poor design for production code because any edit to the program forces the template to change, and the copy is easy to break.
Sources
- Wikipedia: Quine (computing)
- Wikipedia: Kleene's recursion theorem