St_Hakky’s blog

Data Science / Human Resources / Web Applicationについて書きます

Effective python シリーズ2:Follow the PEP 8 Style Guide

こんにちは。

○読んでいる本

以下の本を勉強がてら読んでいます。

www.effectivepython.com

ここにある通り、Pythonプログラムを改良する59項目が掲載されています。詳細は本に書かれているので、それを読めば良しとして、大事そうなところと、これに関連して勉強したことを書きます。

まとめページは以下より。

st-hakky.hatenablog.com


さて、今回は2つ目:「Follow the PEP 8 Style Guide」をやります。

○Follow the PEP 8 Style Guide

デッ、デタ!PEP 8ですね。

www.python.org

ちゃんと読む。割と文字が多すぎるよ系のエラーが辛い。笑

■Zen of python

Pythonの心得的なやつでしょうか。

import this

って打つと、「Zen of python」が出てきます笑。

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!

○PEP 8 checker

pep8というパッケージがあり、これによってpythonコードがPEP 8に従って書かれているかどうかがわかります。pipでインストールが可能です。

pip install pep8

使い方は普通に、コマンドラインから、

pep8 file_name.py

みたいな感じでできる。

・参考
pep8 1.7.1 : Python Package Index

○PEP 8をAtomで使う

私は、Atomを使っているので、PEP8をAtomのエディタ内で使えるものがあれば便利だなと思って探して見ました。以下が入れたもの。

■atom-pep8

普通にインストールして使えばおk。

■linter-python-pep8

普通にインストールして使えばおk。

■linter-pycodestyle

これを使うために、事前にpipでインストールする必要があるみたい。

pip install pycodestyle
■python-autopep8

以下の「python-autopep8」が、自動でpythonのファイルをpep8に準拠して整形してくれるツール。

python-autopep8

atomでこのパッケージを使うようにするには、pipでまずautopep8を入れる必要がある様子。

pip install autopep8

Atom Beautifyと組み合わせて、使えばpep8に自動で変換するだけではなく、コードも自動で整えてくれるので、便利。

http://loumo.jp/wp/archive/20160202120047/

以上。