Search

Search papers and lessons

Self-Reproducing Program

Level 2 · 8 min read

A self-reproducing program, or quine, is a program whose only output is its own source code, and it works by carrying a template of itself as data.

On this page

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 PP whose output equals its own source text. Write src(P)\mathrm{src}(P) for that text, and write run(P)\mathrm{run}(P) for the output of running PP with no input. A quine satisfies

run(P)=src(P).\mathrm{run}(P) = \mathrm{src}(P).

The construction needs a function that turns a string into a quoted, escaped version of itself. Call it quote(s)\mathrm{quote}(s). In Python this is repr, and it is what makes the template insert correctly into itself. The general recipe is:

  1. Write a template TT that contains a placeholder %r\texttt{\%r} for the quoted form of the template.
  2. Build the full program as src(P)=T\mathrm{src}(P) = T with the placeholder filled by quote(T)\mathrm{quote}(T), plus the print statement.
  3. 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 gg that turns programs into programs, there is a program ee such that φe=φg(e)\varphi_e = \varphi_{g(e)}, where φe\varphi_e is the function computed by the program with index ee. In words, a program can be given access to its own description. A quine is the special case where gg 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

Example
A two-line Python quine

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.

  1. The variable s holds the string s = %r followed by a newline and print(s %% s). The %% is an escaped percent sign, so after formatting it becomes a single %.
  2. The expression s % s formats the string. The %r placeholder is replaced by repr(s), which is s quoted with its newline written as \n.
  3. The first line of output is therefore s = followed by the quoted template, which is exactly the first line of the source.
  4. The second line of output is print(s % s), which is exactly the second line of the source, after the %% has become %.
  5. 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.

Example
Why the quoting step matters

Consider a broken attempt with the same structure but without repr.

  1. Let the program be s = 's = "%s"\nprint(s %% s)' on the first line and print(s % s) on the second. The only change is that %r became "%s".
  2. Format it with s % s. The %s inserts 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 %%.
  3. 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.
  4. The remaining output is print(s %% s)" followed by print(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.

SituationWhat goes wrongBetter choice
You need a program's own source for logging or versioningA quine is brittle, and any edit changes the template and breaks the copyEmbed a version constant, or read the file from disk
A language's quoting differs from the one assumedThe output has the right content but the wrong escapes, so the check failsUse the language's own quoting function such as repr, and test the output
Whitespace or newline handling variesThe output differs from the source by a trailing newlineCompare the output with the file in bytes, not visually
A compiler test requires exact outputA quine that prints even one extra character failsKeep 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