46

Python 2.x (30 bytes):

_='_=%r;print _%%_';print _%_

Python 3.x (32 bytes)

_='_=%r;print(_%%_)';print(_%_)

Is this the shortest possible Python quine, or can it be done better? This one seems to improve on all the entries on The Quine Page.

I'm not counting the trivial 'empty' program.

wim
  • 338,267
  • 99
  • 616
  • 750
  • 2
    Won't work with Python 3.x, by the way. – Michael Foukarakis Jun 03 '11 at 05:27
  • 3
    "can it be done better?" Although this question has definitively an answer it is hard to be answered (unless the answer is yes and you have a counterexample). How should someone know without testing ALL possible shorter programs? – Howard Jun 03 '11 at 05:27
  • 2
    @Howard: At some point, there aren't all that many of those... – Nemo Jun 03 '11 at 05:32
  • well, since we're down to <30 characters, and there's a finite symbol set for the syntax, a proof may even be possible by enumeration? but i was more thinking someone might be able to chime in with "I can do better!" after all, this quine is only a slight modification of Frank Stajano's idea from the quine page.. ;) – wim Jun 03 '11 at 05:32
  • @Michael Foukarakis : awww :( what broke it in python 3? new print function? – wim Jun 03 '11 at 06:01
  • Yes, `print` is a function in 3.x, making parentheses mandatory. – Michael Foukarakis Jun 03 '11 at 06:10
  • 11
    For the record, `_='_=%r;print(_%%_)';print(_%_)` works in python3. – Mechanical snail Jul 12 '11 at 02:28
  • 4
    I'd prefer to write it as `r='r=%r;print r%%r';print r%r` (for python2), though. – Mechanical snail Jul 12 '11 at 02:53
  • "[A quine is ***a non-empty computer program*** which takes no input and produces a copy of its own source code as its only output.](https://en.wikipedia.org/wiki/Quine_(computing))". So, an 'empty' program isn't a Quine. – YaOzI Mar 20 '16 at 08:55
  • @Mechanicalsnail: You need a trailing newline. – Eric Duminil Mar 17 '18 at 19:37
  • The shortest quine is 1 byte shorter than this actually, on code.golf – DialFrost Jan 05 '23 at 23:18
  • 1
    @DialFrost Interesting, you're right - the top submissions [there](https://code.golf/quine#python) are 31 bytes. I wonder what that is (I can't see the solutions) – wim Jan 06 '23 at 02:18

11 Answers11

72

I'm just going to leave this here (save as exceptionQuine.py):

    File "exceptionQuine.py", line 1
        File "exceptionQuine.py", line 1
        ^
IndentationError: unexpected indent
Beurtschipper
  • 863
  • 6
  • 13
23

Technically, the shortest Python quine is the empty file. Apart from this trivial case:

Since Python's print automatically appends a newline, the quine is actually _='_=%r;print _%%_';print _%_\n (where \n represents a single newline character in the file).

Mechanical snail
  • 29,755
  • 14
  • 88
  • 113
  • 1
    hmm, you are right. alternatively , perhaps the new line can be suppressed like `r='r=%r;print r%%r,';print r%r,` – wim Jul 12 '11 at 03:18
  • That would be 1 character longer, and it wouldn't work in python3. – Mechanical snail Jul 12 '11 at 18:48
  • @wim: 1 character (on Linux). – Mechanical snail Jul 13 '11 at 04:22
  • 3
    @wim: I mean there should be an actual newline in the file, but stackoverflow doesn't make it easy to write. – Mechanical snail Jul 13 '11 at 08:18
  • 4
    I don't think "Technically, the shortest Python quine is the ***empty file***.". Because: "[A quine is **a non-empty computer program** which takes no input and produces a copy of its own source code as its only output.](https://en.wikipedia.org/wiki/Quine_(computing))". – YaOzI Mar 20 '16 at 08:51
14

Both

print open(__file__).read()

and anything involving import are not valid quines, because a quine by definition cannot take any input. Reading an external file is considered taking input, and thus a quine cannot read a file -- including itself.

For the record, technically speaking, the shortest possible quine in python is a blank file, but that is sort of cheating too.

wintermute
  • 165
  • 1
  • 2
  • 5
    "For the record, technically speaking, the shortest possible quine in python is a blank file, but that is **sort of cheating** too." Correction: it **is** cheating. – EKons Apr 14 '16 at 13:51
13

In a slightly non-literal approach, taking 'shortest' to mean short in terms of the number of statements as well as just the character count, I have one here that doesn't include any semicolons.

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

In my mind this contends, because it's all one function, whereas others are multiple. Does anyone have a shorter one like this?

Edit: User flornquake made the following improvement (backticks for repr() to replace str() and shave off 6 characters):

print(lambda x:x+`(x,)`)('print(lambda x:x+`(x,)`)',)
postylem
  • 1,185
  • 12
  • 26
11

Even shorter:

print(__file__[:-3])

And name the file print(__file__[:-3]).py (Source)

Edit: actually,

print(__file__)

named print(__file__) works too.

OlivierBlanvillain
  • 7,701
  • 4
  • 32
  • 51
  • 5
    Nice abuse of the rules ;) – Tino Feb 22 '15 at 04:40
  • 1
    upvote, it's good :) I can't help but feel quine program is nicer if it works independently of the filename though – wim Feb 18 '16 at 03:45
  • This cheat works with `gcc`, too (following needs `bash`): `a=$'main(){write(1,__FILE__,29);}'; echo -n "$a" > "$a.c"; gcc "$a.c"; ./a.out | cmp - "$a.c"; echo $?` (note, this does not contain any linebreaks) – Tino Dec 20 '16 at 17:38
  • 15 bytes+15 bytes for filename=30 bytes by PPCG scoring. Not quite good enough. – CalculatorFeline May 28 '17 at 05:18
7

Python 3.8

exec(s:='print("exec(s:=%r)"%s)')
RaminNietzsche
  • 2,683
  • 1
  • 20
  • 34
6

Here is another similar to postylem's answer.

Python 3.6:

print((lambda s:s%s)('print((lambda s:s%%s)(%r))'))

Python 2.7:

print(lambda s:s%s)('print(lambda s:s%%s)(%r)')
Tim
  • 76
  • 2
  • 4
3

As of Python 3.8 I have a new quine! I'm quite proud of it because until now I have never created my own. I drew inspiration from _='_=%r;print(_%%_)';print(_%_), but made it into a single function (with only 2 more characters). It uses the new walrus operator.

print((_:='print((_:=%r)%%_)')%_)

2

I would say:

print open(__file__).read()

Source

manojlds
  • 290,304
  • 63
  • 469
  • 417
0

This one is least cryptic, cor is a.format(a) a="a={1}{0}{1};print(a.format(a,chr(34)))";print(a.format(a,chr(34)))

miroB
  • 468
  • 6
  • 8
-24

I am strictly against your solution.

The formatting prarameter % is definitively a too advanced high level language function. If such constructs are allowed, I would say, that import must be allowed as well. Then I can construct a shorter Quine by introducing some other high level language construct (which, BTW is much less powerful than the % function, so it is less advanced):

Here is a Unix shell script creating such a quine.py file and checking it really works:

echo 'import x' > quine.py
echo "print 'import x'" > x.py
python quine.py | cmp - quine.py; echo $?

outputs 0

Yes, that's cheating, like using %. Sorry.

Tino
  • 9,583
  • 5
  • 55
  • 60
  • 12
    `%` is just a language function, like concatenation or multi-line strings. Using external resources (like an extra file that's not included in the quine) is plain cheating. – BoppreH Oct 24 '13 at 01:21
  • Actually, `import` is just a language function, like concatenation or multi-line strings. Using external ressources (like using `#include ` in C or linking the standard library) is perfectly valid in quines (else there would be no quines in compiled languages). However there is a good cause why not to allow too advanced high level functions in a language, like languages allowing introspection (and there are introspection modules for Python readily available). Hence what I wrote: The consequence from outlawing `import` is to outlaw `%`, too. Sorry folks! – Tino Dec 07 '13 at 16:22
  • 5
    Do you outlaw %s in C quines, too? – Patrick Collins Apr 20 '14 at 04:18
  • I definitively call it cheating. `printf` is a high level library function, not a basic language construct. If you implement something like `printf` in your quine that is ok. But abstain from higher level library functions, only use basic I/O, please! – Tino Apr 21 '14 at 00:58
  • Adding one thing: The only thing where the use of the `printf` function could be acceptable in C Quines is for the (exact!) usage `printf("%s",s)` in situations, where `printf(s)` might abuse the formatting function of `printf`. Compare `f=printf;o="%s";f(o,s)` saves 1 byte compared to `f=fputs;o=stdout;f(s,o)`. I would call this the only possibly legitimate use of `printf` (or `%s`) in C Quines. There might be similar uses of `%` in Python, but I don't think those constructs are shorter than the direct output. – Tino Apr 21 '14 at 01:29
  • 6
    As far as I am aware, the purpose of a quine is to write a program that outputs its own source without external inputs. % does not use an external source. Import can be viewed in two ways. Either you consider the second file an external source (thus breaking the rules) or you consider the imported code as part of the source, in which case your quine does not print out the "full source". Thus % does not violate quine rules, and your import does. – vastlysuperiorman Feb 20 '15 at 01:12
  • @vastlysuperiorman: `touch nix.py; python nix.py | cmp nix.py -`. However `nix.py` (the empty file) is no quine. Read: With quines, it's simply is not that simple as you probably think. Also: import does not use external sources, as this is compile time, not runtime. – Tino Feb 22 '15 at 04:28
  • 1
    @Tino You "outlawed" `import` statements [here](/questions/6223285#comment30541410_18831770) – EKons Apr 19 '16 at 15:04
  • 1
    @ΈρικΚωνσταντόπουλος If you agree to my statement there, you also agree, that `%` is cheating!?! As my argument is: `%` is cheating, iff `import` is cheating. This means, either we allow both, or none. And again, I repeat: `import` is not accessing external resources like `#include ` isn't cheating and linking in standard C libraries isn't, too. Only using too high level functions is cheating! And my argument is, that `import` is even a lower level construct than `%`! So using any is cheating. BTW: Why am I downvoted while http://stackoverflow.com/a/18521084 is upvoted? – Tino Dec 20 '16 at 17:13
  • @Tino Please cool down a bit. `%r` is just 2 characters of the string. The operator `%` that uses them is just an operator, not an external thing. The `repr` builtin is also a builtin, not a high-level function. – EKons Dec 20 '16 at 17:34
  • @ΈρικΚωνσταντόπουλος Thanks for noting this! Until now I focused entirely on `print _%_` being something like `printf(a, a)` which usually is considered cheating in C quines. I fully oversaw this `%r` which is even worse! It uses `repr()`, which is language introspection. Do you really think, language introspection shall be allowed in quines? – Tino Dec 20 '16 at 18:09
  • 2
    @Tino I can't seem to understand you I guess. Also, why shouldn't it be allowed? It's just that you can't read input and you can't have an empty program. – EKons Dec 20 '16 at 18:12
  • @ΈρικΚωνσταντόπουλος Sorry, I meant [Reflection](https://en.wikipedia.org/wiki/Reflection_(computer_programming)). Reflection allows a program to look at its own source code. [This commonly is considered cheating in quines.](https://en.wikipedia.org/wiki/Quine_(computing)#.22Cheating.22_quines) Please note that we are at 13 comments for 13 downvotes now. So I thank you very much to reach the recommendation for ["a comment per downvote"](http://meta.stackexchange.com/a/2373) without need for spam. I'll now stop commenting until the need for comments arises again. Merry Xmas! – Tino Dec 20 '16 at 18:48
  • 1
    [PPCG has a good definition of quines](https://codegolf.meta.stackexchange.com/questions/4877/what-counts-as-a-proper-quine).`repr()` does _not_ use reflection. It is a standard function that takes string inputs and outputs other strings. An example would be does `repr(input())` read the source at all? The string just happens to include part of the source, as the source defines the string (As what else would when hard-coding a string?). And `%` on a string is just string formatting. Formatting is also a function that doesn't rely on the source, just the arguments (i.e. no side effects.) – Artyer Jun 02 '17 at 19:26
  • Saying `%` is invalid is like saying recursion is invalid. `%` accesses a string, not the program itself. Recursion accesses a function, not the program (however, recursion would be invalid for function quines) – MilkyWay90 Mar 02 '19 at 16:35