初めに
Pythonを書くようになり、Pythonicがなにかわからなくなったので、まとめ直す。
Pythonicとは
あなたのPythonインタープリタで
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!
という文章が出てくる。
Pythonic はこのThe Zen of Pythonに則ったものをいうらしい。
つまりPythonの言語設計思想に沿った、簡潔で読みやすく、効率的なコードの書き方を指す。単に文法的に正しいだけでなく、Pythonらしい慣習やイディオムをうまく使って、Pythonの機能を最大限に引き出すことを意味する。
具体例
-
命名規則を守る
変数にはスネークケース、クラスにはパスカルケースを使う。pythonic_name = 10 class PythonicClass: pass unPythonicName = 10 class un_pythonic_class: pass -
同じ処理は「for + if + append」ではなく 内包表記(list comprehension) を使う
悪い例:result = [] for x in items: if x > 10: result.append(x * 2)Pythonic:
result = [x * 2 for x in items if x > 10]こちらの方が読みやすい -
文字列の結合は + より join
悪い例:msg = "" for s in strings: msg += sPythonic:
msg = "".join(strings) -
例外を正しく使う(エラーは無視しない)
悪い例:try: risky() except: passPythonic:
try: risky() except ValueError: handle() -
Truthy/Falsyを活用する
悪い例:if len(items) != 0: ...Pythonic:
if items: ... -
enumerate()とzip()を上手に使う
悪い例:i = 0 for item in items: print(i, item) i += 1Pythonic:
for i, item in enumerate(items): print(i, item)for a, b in zip(list1, list2): ...手動でインデックスを回すな
-
with を使って安全にリソース管理
悪い例:f = open("a.txt") data = f.read() f.close()Pythonic:
with open("a.txt") as f: data = f.read() -
EAFP(やってみてダメなら例外処理)を採用
例:try: value = d[key] except KeyError: value = default
終わりに
Elephant
~Thank you for reading~