LoginSignup
10
7

More than 5 years have passed since last update.

AWS Cloud9でyapfを使ってPythonコードを自動整形する

Last updated at Posted at 2018-03-04

AWS Cloud9にyapfを導入

AWS Cloud9ではCustom Code Formatterを設定できるので
ファイル保存時にyapfを実行し、
Pythonコードをフォーマットするようにしたいと思います

yapfとは

yapf( https://github.com/google/yapf )とは
Pythonのコードフォーマッターで、
次の例のようにコードを綺麗にフォーマットしてくれます

フォーマット前

x = {  'a':37,'b':42,

'c':927}

y = 'hello ''world'
z = 'hello '+'world'
a = 'hello {}'.format('world')
class foo  (     object  ):
  def f    (self   ):
    return       37*-+2
  def g(self, x,y=42):
      return y
def f  (   a ) :
  return      37+-+a[42-x :  y**3]

フォーマット後

x = {'a': 37, 'b': 42, 'c': 927}

y = 'hello ' 'world'
z = 'hello ' + 'world'
a = 'hello {}'.format('world')


class foo(object):
    def f(self):
        return 37 * -+2

    def g(self, x, y=42):
        return y


def f(a):
    return 37 + -+a[42 - x:y**3]

コマンドだと下記のように実行します

$ yapf -i sample.py

設定手順

yapfをインストール

sudo pip install yapf

Custom Code Formatterの設定

AWS Cloud9の「Preferences」の「Python Support」の中に
「Custom Code Formatter」の欄があるので、

yapf -i "$file"

と書きます

スクリーンショット 2018-03-04 12.24.43.png

以上で設定完了です。
コードを保存すると、自動でフォーマットしてくれます。

フォーマットスタイルのカスタマイズ

フォーマットスタイルはデフォルトではpep8になっていますが、
好みに合わせてカスタマイズできます

詳細はこちらにあります
https://github.com/google/yapf

10
7
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
10
7