Zen of Python
From Wikipedia, the free encyclopedia

Zen of Pythonとは、Pythonプログラミング言語に影響を与えたコンピュータプログラムを書くための19の「原則」を集めたものである[1]。これらの原則に沿ったPythonのコードはしばしば「Pythonic」と呼ばれる[2]。
ソフトウェア工学者のティム・ピーターズがこの原則集を書き、1999年にPythonのメーリングリストに投稿した[3]。ピーターズによる原則集では、Python言語の原作者のグイド・ヴァンロッサムに言及した「グイドが埋める」とされた20番目の原則が空のまま残されていた。20番目の原則は空のまま埋められていない。
ピーターズによるZen of Pythonは20番目の公式のPython Enhancement Proposal(PEP)として文書化され、パブリックドメインで公開された[4]。また、Zen of PythonはPythonインタプリタにイースターエッグとして含まれており、import thisと入力することで表示できる[1][4][注釈 1]。
2020年5月、GNU Mailmanの開発者のBarry Warsawが歌の歌詞としてZen of Pythonを使用した[5][6]。

原則は以下の通りである[注釈 2]:
- 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.[注釈 3]
- 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.[注釈 4]
- 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!
Pythonicであること
原則の1つである「There should be one-- and preferably only one --obvious way to do it」は「Pythonic」な方法と言うことができる[8]。「Pythonic」の公式な定義は以下の通りである[2]:
他の言語で一般的な考え方で書かれたコードではなく、Python の特に一般的なイディオムに従った考え方やコード片。例えば、Python の一般的なイディオムでは
for文を使ってイテラブルのすべての要素に渡ってループします。他の多くの言語にはこの仕組みはないので、Python に慣れていない人は代わりに数値のカウンターを使うかもしれません:for i in range(len(food)): print(food[i])これに対し、きれいな Pythonic な方法は:
for piece in food: print(piece)
理解するのが難しいコードや他のプログラミング言語から大まかに転写したように読めるコードは「unpythonic」と呼ばれている[9]。
実践
Zen of Pythonの公開以来、その効果と開発者の間での実際の使用に関する調査が行われてきた。初心者と経験豊富なPythonプログラマーの間の解釈の違いにも関わらず、様々な能力を持つ13人のPythonプログラマーに対するインタビューでは、Zen of Pythonが「開発者がコードを書いたりコードについて話したりする方法に良い影響を与えている」ことが示されている[8]。研究者はこのケーススタディーを拡張してGitHubリポジトリでのPythonイディオムの使用を調査し、「Pythonicイディオム」[注釈 5]の使用量が時間の経過とともに増加していることを発見した[10]。Zen of Pythonに沿ってPythonコードを記述すると、Pythonプログラムのメモリ使用量と実行時間を節約できる可能性がある[11]。Pythonicなコードを書きたいという要求から、プログラマーがこの目標を達成できるようにするためのリファクタリングツールが開発された[12][13]。