長い条件式を行に分割する 質問する

長い条件式を行に分割する 質問する

次のような if ステートメントがいくつかあります。

def is_valid(self):
    if (self.expires is None or datetime.now() < self.expires)
    and (self.remains is None or self.remains > 0):
        return True
    return False

この式を入力すると、Vim は自動的に行andと同じインデントで新しい行に移動しますif。インデントの組み合わせをさらに試してみましたが、検証では常に無効な構文であると表示されます。長い if を作成するにはどうすればよいでしょうか?

ベストアンサー1

条件全体を囲む括弧のレベルをさらに追加します。これにより、必要に応じて改行を挿入できるようになります。

if (1+1==2
  and 2 < 5 < 7
  and 2 != 3):
    print 'yay'

実際に使用するスペースの数については、Python スタイルガイド何も義務付けているわけではありませんが、いくつかのアイデアを提供しています:

# No extra indentation.
if (this_is_one_thing and
    that_is_another_thing):
    do_something()

# Add a comment, which will provide some distinction in editors
# supporting syntax highlighting.
if (this_is_one_thing and
    that_is_another_thing):
    # Since both conditions are true, we can frobnicate.
    do_something()

# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
        and that_is_another_thing):
    do_something()

おすすめ記事