Pocooのスタイルガイド Pocoo Styleguide

Pocooのスタイルガイドは、Flaskを含む、Pocooのすべてのプロジェクト用のスタイルガイドです。このスタイルガイドはFlaskへのパッチに対しては要求事項であり、Flask拡張に対しては推奨事項です。 The Pocoo styleguide is the styleguide for all Pocoo Projects, including Flask. This styleguide is a requirement for Patches to Flask and a recommendation for Flask extensions.

全体的にPocoo StyleguideはPEP 8に密接に従いながら、いくつかの小さな違いや拡張を伴っています In general the Pocoo Styleguide closely follows :pep:`8` with some small differences and extensions.

レイアウトの原則 General Layout

インデント Indentation:

実際のスペース4文字。タブは含めず、例外はありません。 4 real spaces. No tabs, no exceptions.

行の最長文字数 Maximum line length:

79文字で、もし絶対に必要な場合には84までという緩やかな制限を伴います。break, continueそしてreturn文を賢く使って、ネストしすぎたコードを避けるようにしてください。 79 characters with a soft limit for 84 if absolutely necessary. Try to avoid too nested code by cleverly placing `break`, `continue` and `return` statements.

長い行の継続: Continuing long statements:

文を続けるにはバックスラッシュを使用でき、その場合は最後のドットまたは等号記号で次の行をそろえるか、スペース4文字でインデントします: To continue a statement you can use backslashes in which case you should align the next line with the last dot or equal sign, or indent four spaces::

this_is_a_very_long(function_call, 'with many parameters') \
    .that_returns_an_object_with_an_attribute

MyModel.query.filter(MyModel.scalar > 120) \
             .order_by(MyModel.name.desc()) \
             .limit(10)

もし丸カッコや大カッコを使って文の中で(行を)分ける場合、カッコに揃えます: If you break in a statement with parentheses or braces, align to the braces::

this_is_a_very_long(function_call, 'with many parameters',
                    23, 42, 'and even more')

多くのアイテムがあるリストやタプルに対しては、開きカッコの直後で(行を)分けます: For lists or tuples with many items, break immediately after the opening brace::

items = [
    'this is the first', 'set of items', 'with more items',
    'to come in this line', 'like this'
]
空行 Blank lines:

トップレベルの関数とクラスは2行で分け、その他は全て1行で分けます。コードの中で論理的な塊を分けるために空行を使い過ぎないようにします: Top level functions and classes are separated by two lines, everything else by one. Do not use too many blank lines to separate logical segments in code. Example::

def hello(name):
    print 'Hello %s!' % name


def goodbye(name):
    print 'See you %s.' % name


class MyClass(object):
    """This is a simple docstring"""

    def __init__(self, name):
        self.name = name

    def get_annoying_name(self):
        return self.name.upper() + '!!!!111'

式と文 Expressions and Statements

原則となる空白文字のルール General whitespace rules:
  • 単語ではない単項演算子(例: -, ~など)に対しては、カッコの内側と同様に空白文字を使いません。 No whitespace for unary operators that are not words (e.g.: ``-``, ``~`` etc.) as well on the inner side of parentheses.

  • 二項演算子の間には空白文字を置きます。 Whitespace is placed between binary operators.

良い: Good::

exp = -1.05
value = (item_value / item_count) * offset / exp
value = my_list[index]
value = my_dict['key']

悪い: Bad::

exp = - 1.05
value = ( item_value / item_count ) * offset / exp
value = (item_value/item_count)*offset/exp
value=( item_value/item_count ) * offset/exp
value = my_list[ index ]
value = my_dict ['key']
ヨーダ文(訳注: 定数を左側に、変数を右側に配置する書き方のことだと思います)は使いません: Yoda statements are a no-go:

定数に対して変数を使った比較は決してせず、常に変数に対して定数を使います: Never compare constant with variable, always variable with constant:

良い: Good::

if method == 'md5':
    pass

悪い: Bad::

if 'md5' == method:
    pass
比較 Comparisons:
  • 任意の型に対して: ==!= against arbitrary types: ``==`` and ``!=``

  • シングルトン(訳注: デザインパターンのシングルトンのように、プログラム実行中はプログラム内で1つの実体だけ作成されて使い回しされるもの、例えば「None」のようなもののことだと思います)に対してはisis notを使います(例: foo is not None against singletons with ``is`` and ``is not`` (eg: ``foo is not None``)

  • 何かに対してTrueまたはFalseを使った比較は決してしないようにします(例えばfoo == Falseは決して使わず、代わりにnot fooを使います) never compare something with ``True`` or ``False`` (for example never do ``foo == False``, do ``not foo`` instead)

帰属チェックの否定 Negated containment checks:

not foo in barの代わりにfoo not in barを使います use ``foo not in bar`` instead of ``not foo in bar``

インスタンスのチェック Instance checks:

type(A) is Cの代わりにisinstance(a, C)を使いますが、一般的にはインスタンスチェックは避けるようにします。(Pythonなどの)機能を調べましょう(Check for features)。 ``isinstance(a, C)`` instead of ``type(A) is C``, but try to avoid instance checks in general. Check for features.

命名規約 Naming Conventions

  • クラス名: CamelCaseで、省略語部分は大文字を保つようにします(HttpWriterではなくHTTPWriter Class names: ``CamelCase``, with acronyms kept uppercase (``HTTPWriter`` and not ``HttpWriter``)

  • 変数名: lowercase_with_underscores(アンダースコアを使った小文字) Variable names: ``lowercase_with_underscores``

  • メソッドおよび関数名: lowercase_with_underscores(アンダースコアを使った小文字) Method and function names: ``lowercase_with_underscores``

  • 定数: UPPERCASE_WITH_UNDERSCORES(アンダースコアを使った大文字) Constants: ``UPPERCASE_WITH_UNDERSCORES``

  • 事前コンパイルされた正規表現: name_re(訳注: re.compileのようにprecompileした正規表現を格納する変数名には最後に「_re」を付けるという意味合いだと思います) precompiled regular expressions: ``name_re``

保護されるメンバー(訳注: 例えばクラスの内部でしか使わない変数や関数など、外部からのアクセスは避けるべきもの)はアンダースコア1文字を接頭辞にします。アンダースコア2文字(の接頭辞)はmixinクラス用に予約しておきます。 Protected members are prefixed with a single underscore. Double underscores are reserved for mixin classes.

キーワードを使ったクラスでは最後にアンダースコアが追加されます。ビルトイン(訳注: Pythonを実行すると最初から存在するオブジェクトなど)との衝突は許されており、変数名の最後にアンダーラインを追加することで解決させてはいけません。もし関数が(訳注: 後から作成したオブジェクトなどに名前を使われたことで)隠れてしまったビルトインへアクセスする必要がある場合、ビルトインを代わりに異なる名前で改めてバインドします。 On classes with keywords, trailing underscores are appended. Clashes with builtins are allowed and **must not** be resolved by appending an underline to the variable name. If the function needs to access a shadowed builtin, rebind the builtin to a different name instead.

関数およびメソッドの引数: Function and method arguments:
  • クラスメソッド: 最初の引数としてcls class methods: ``cls`` as first parameter

  • インスタンスメソッド: 最初の引数としてself instance methods: ``self`` as first parameter

  • プロパティーに対するlambdaは、display_name = property(lambda x: x.real_name or x.usernameのように、最初の引数をxで置き換えているかもしれません lambdas for properties might have the first parameter replaced with ``x`` like in ``display_name = property(lambda x: x.real_name or x.username)``

Docstrings

Docstringの規約: Docstring conventions:

すべてのdocstringはSphinxによって理解されるようにreStructuredTextを使って整形されます。docstringの行数によって、異なる形で置かれます。もし1行だけならば、閉じる引用符3文字は開くmのと同じ行にし、それ以外ではテキストは開く引用符と同じ行で始め、文字列を閉じる引用符3文字はそれ自身の行を持つようにします: All docstrings are formatted with reStructuredText as understood by Sphinx. Depending on the number of lines in the docstring, they are laid out differently. If it's just one line, the closing triple quote is on the same line as the opening, otherwise the text is on the same line as the opening quote and the triple quote that closes the string on its own line::

def foo():
    """This is a simple docstring"""


def bar():
    """This is a longer docstring with so much information in there
    that it spans three lines.  In this case the closing triple quote
    is on its own line.
    """
モジュールのヘッダー Module header:

モジュールのヘッダーはutf-8のエンコーディング宣言(ASCIIではない文字が使われる場合ですが、そうでない場合でも宣言することが推奨されます)と標準的なdocstringから構成します: The module header consists of a utf-8 encoding declaration (if non ASCII letters are used, but it is recommended all the time) and a standard docstring::

# -*- coding: utf-8 -*-
"""
    package.module
    ~~~~~~~~~~~~~~

    A brief description goes here.

    :copyright: (c) YEAR by AUTHOR.
    :license: LICENSE_NAME, see LICENSE_FILE for more details.
"""

適切なcopyrightsとlicenseのファイルがapproved Flask extensionsでは必要であることを覚えておいてください。 Please keep in mind that proper copyrights and license files are a requirement for approved Flask extensions.

コメント Comments

コメントに対するルールはdocstringと似ています。どちらもreStructuredTextを使って整形されます。もし属性を文書化するためにコメントが使われる場合、コメントを始めるパウンド記号(#)の後にコロンを置きます: Rules for comments are similar to docstrings. Both are formatted with reStructuredText. If a comment is used to document an attribute, put a colon after the opening pound sign (``#``)::

class User(object):
    #: the name of the user as unicode string
    name = Column(String)
    #: the sha1 hash of the password + inline salt
    pw_hash = Column(String)