0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

  • Python には、いくつかのイースターエッグが隠されています
  • 実際にいくつかのイースターエッグを試してみました
  • 基本的に Ubuntu (WSL) 上の Python 3.10.12 (ちょっと古い版)で試しています(が、別の環境確認したものもあります)

The Zen of Python

まずは、非常に有名な Zen of Python です。

python を起動して import this と入力すると、Zen of Python が表示されます。

$ python3
(バージョン情報は省略)
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>> print(this.__spec__)
ModuleSpec(name='this', loader=<_frozen_importlib_external.SourceFileLoader object at 0x75877843f5e0>, origin='/usr/lib/python3.10/this.py')
>>>

このソースコードは私の環境では /usr/lib/python3.10/this.py にあるようです。

/usr/lib/python3.10/this.py
s = """Gur Mra bs Clguba, ol Gvz Crgref

Ornhgvshy vf orggre guna htyl.
Rkcyvpvg vf orggre guna vzcyvpvg.
Fvzcyr vf orggre guna pbzcyrk.
Pbzcyrk vf orggre guna pbzcyvpngrq.
Syng vf orggre guna arfgrq.
Fcnefr vf orggre guna qrafr.
Ernqnovyvgl pbhagf.
Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.
Nygubhtu cenpgvpnyvgl orngf chevgl.
Reebef fubhyq arire cnff fvyragyl.
Hayrff rkcyvpvgyl fvyraprq.
Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff.
Gurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg.
Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.
Abj vf orggre guna arire.
Nygubhtu arire vf bsgra orggre guna *evtug* abj.
Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.
Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.
Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!"""

d = {}
for c in (65, 97):
    for i in range(26):
        d[chr(i+c)] = chr((i+13) % 26 + c)

print("".join([d.get(c, c) for c in s]))

いろいろなところで紹介されいるので、知っている方も多いと思いますが、これは ROT13 という方式で難読化(暗号化)されています。
復号してみると、Zen of Python の文章が出力されます。

この Zen of Python は PEP 20 で定義されており、Python の設計哲学を表す文章らしいです。

Qiita でも何度も紹介されいるので、詳細は秀逸な紹介ページを参照してください。

おまけで、Wikipedia も。

Hello world!

以下のように import __hello__ と入力すると、Hello world! が表示されます。

$ python3
Python 3.10.12 (main, Mar  3 2026, 11:56:32) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import __hello__
Hello world!
>>> print(__hello__.__spec__)
ModuleSpec(name='__hello__', loader=<class '_frozen_importlib.FrozenImporter'>, origin='frozen')
>>> import __phello__.spam
Hello world!
Hello world!
>>>

これは、Frozen Module という仕組みで、CPython の実行環境に組み込まれているモジュールのようです。origin が frozen となっているのがそれを示しています。

CPython には、Frozen Module としてPythonの実行環境にモジュールを組み込むことのできる仕掛けがあります。この __hello__ はその一つで、動作確認用に組み込まれているモジュールのようです。

__hello__ はテスト用モジュールで、 __phello__ はテスト用パッケージになっており、__phello__.spam というモジュールが含まれているようです。

3.11 からは import しただけでは Hello World が表示されなくなったようで、その後に __hello__.main() を実行する必要があるようです。

最新版のソースを見ると __phello__.ham.eggs というモジュールも追加されているように見えます(試してません)。

antigravity

以下のように import antigravity と入力すると、(ブラウザが起動できるようになっていれば)ブラウザが起動して XKCD の漫画が表示されます。

XKCD というのは、アメリカの Web コミックで、プログラマや技術者向けのネタが多い漫画です。

$ python3
(省略)
>>> import antigravity
>>> print(antigravity.__spec__)
ModuleSpec(name='antigravity', loader=<_frozen_importlib_external.SourceFileLoader object at 0x744b97f3d030>, origin='/usr/lib/python3.10/antigravity.py')
/usr/lib/python3.10/antigravity.py

import webbrowser
import hashlib

webbrowser.open("https://xkcd.com/353/")

def geohash(latitude, longitude, datedow):
    '''Compute geohash() using the Munroe algorithm.

    >>> geohash(37.421542, -122.085589, b'2005-05-26-10458.68')
    37.857713 -122.544543

    '''
    # https://xkcd.com/426/
    h = hashlib.md5(datedow, usedforsecurity=False).hexdigest()
    p, q = [('%f' % float.fromhex('0.' + x)) for x in (h[:16], h[16:32])]
    print('%d%s %d%s' % (latitude, p[1:], longitude, q[1:]))

ソースを見るとわかるように、import をすると自動的に https://xkcd.com/353/ にアクセスするようになっています。
この漫画は「Python を使えばいろいろなことがシンプルに実現できる。 import antigravity とタイプしたら空を飛べた」という内容になっています(たぶん。詳細は実際にコミックを見てください)。

ちなみに、同じソースに geohash という関数が定義されています。一般的に GeoHash といえば、位置情報を短い文字列に変換するアルゴリズムのことを指すようですが、それとは全く関係ないようです。

XKCD の漫画の中で(コメントにある https://xkcd.com/426/ のこと)、緯経度情報とその日(または直前)のダウ平均の始値をもとに計算して新たな位置情報を作って、そこを目的地とするというゲーム?が紹介されており、そのアルゴリズムを実装したもののようです。

PEP 401 - BDFL Retirement

python には __future__ というモジュールがあり、将来のバージョンで追加される予定の機能を先行して使えるようにするための仕組みがあります。
機能を指定して import すると、その機能が有効になり、将来のバージョンでその機能が有効になったときと同じように文法と挙動が切り替わります。

また import するソースファイル(私の環境では /usr/lib/python3.10/__future__.py )や C 言語のソースを見てみると、ドキュメントに記載のない barry_as_FLUFL という名前の機能が定義されていることがわかります。

この barry_as_FLUFL をインポートしてみると、通常の != 演算子が使えなくなり、代わりに <> 演算子が使えるようになります。

$ python3
(省略)
>>> 1 != 2
True
>>> 1 <> 2
  File "<stdin>", line 1
    1 <> 2
      ^^
SyntaxError: invalid syntax
>>> from __future__ import barry_as_FLUFL
>>> 1 != 2
  File "<stdin>", line 1
    1 != 2
      ^^
SyntaxError: with Barry as BDFL, use '<>' instead of '!='
>>> 1 <> 2
True
>>>

これは PEP 401 で定義されている機能のようです。具体的には「Official Acts of the FLUFL」の中の箇条書きの2番めで、以下のように記載のある機能です。

  • Recognized that the != inequality operator in Python 3.0 was a horrible, finger pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling. This change is important enough to be implemented for, and released in Python 3.1. To help transition to this feature, a new future statement, from __future__ import barry_as_FLUFL has been added.

ちなみに、PEP 401 は 2009年4月1日に発行されており、Status は April Fool! になっている、つまりエイプリルフールジョークのようです。

さらに PEP 0 の PEP Index を見てみると、PEP 401 は「Rejected, Superseded, and Withdrawn PEPs(却下、置き換え、撤回されたPEP)」にリストされていることがわかります。却下されたのに、なぜか実装されたままなんですね。それとも最新版では削除されているかな。

PEP の番号が 401 で4月01日に関連しているように思えるのは、意図したものなのか、偶然なのか……。

インデントを波カッコ(ブレース)に変更する

上記の __future__ で文法を切り替えられるという話をしました。

Python ではインデントでブロックを表現しますが、いくつかの言語のようにブロックを波カッコ(ブレース; braces)で表現するように切り替えることもできるでしょうか?

$ python3
(省略)
>>> from __future__ import braces
  File "<stdin>", line 1
SyntaxError: not a chance
>>>

通常のエラーではなく、「not a chance(絶対にありえない)」というエラーメッセージが表示されます。

CPythonのソースを見てみると……。

わざわざ、専用の処理があるようです。

無限のハッシュ値

Python で、無限のハッシュ値を求めてみると、なんとなく円周率っぽい答えが出ます。

$ python3
(省略)
>>> hash(float('inf'))
314159
>>> hash(float('-inf'))
-314159
>>>

これは、計算した結果偶然こうなったわけではなく、ソースコードにハードコーディングされているようです。

ソースコードの rot13 エンコード

昔の Python2 のころの話ですが、Python のソースコードを rot13 でエンコードすることができたようです。

#!/usr/bin/env python2
# -*- coding: rot13 -*-
cevag "Hello, World!"
$ chmod a+x rot13.py
$ ./rot13.py
Hello, World!

手元には Python2.7 しかなかったので、それで確認しましたが print 部分を rot13 した cevag しても、ちゃんと Hello, World! と表示されました。
文字列部分はそのままのようですね。

Python3 ではうまくいかないようです( SyntaxError: encoding problem: rot13 になる)。

Peg Parser

Python 3.9 だけだと思いますが、以下の様な変わったエラー「You found it!(見つけましたね!)」が出ることがあります。

$ python3.9
(省略)
>>> __peg_parser__
  File "<stdin>", line 1
    __peg_parser__
    ^
SyntaxError: You found it!

これは、Python3.9 でパーサーの切り替え( PEP 617 )が行われるときに埋め込まれたイースターエッグだそうです。
Python3.10 ではこのイースターエッグは削除されたとのこと( https://bugs.python.org/issue40939 )。
(近くの RHEL9 に入っていた Python3.9 で確認しました)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?