Pythonにおける条件分岐のベストプラクティス

Pythonにおける条件分岐のベストプラクティス

この記事ではPythonにおける条件分岐のベストプラクティスについて説明します。

YouTube Video

Pythonにおける条件分岐のベストプラクティス

Pythonのif文は、条件分岐を実現するための基本的な構文であり、コードの読みやすさや保守性に大きな影響を与えます。ここでは、if文を使う際のベストプラクティスについて詳しく解説します。

明示的な条件式を使用する

条件式は簡潔かつ明示的に記述し、冗長な記述は避けます。

1condition = True
2
3### Bad Example
4if condition == True:
5    pass
6
7### Good Example
8if condition:
9    pass
  • Pythonでは、if condition:と書くことで、条件が真である場合を示せます。

複数条件の組み合わせ

複数の条件を組み合わせる場合、andorを使用します。ただし、条件式が複雑になると可読性が低下するため、以下のように工夫します。

 1age = 15
 2is_student = True
 3
 4### Bad Example
 5# Complex condition
 6if (age > 18 and age < 65) or (is_student and age > 15):
 7    pass
 8
 9### Good Example
10# Improving readability
11is_working_age = 18 < age < 65
12is_eligible_student = is_student and age > 15
13
14if is_working_age or is_eligible_student:
15    pass
  • 条件を分割して変数に代入することで、可読性が向上します。

and/orの早期終了(ショートサーキット)

andorを使う条件式では、左側の値だけで結果が確定できるとき、右側の評価を行わない「早期終了(ショートサーキット)」が発生します。これを理解しておくと、無駄な処理を避けたり、エラーを防止できたりします。

 1user = None
 2def expensive_check():
 3    return True
 4
 5# Example of short-circuiting with 'and'
 6if user and user.is_active:
 7    # If user is None, user.is_active will NOT be evaluated
 8    print("Active user found.")
 9
10# Example of short-circuiting with 'or'
11if user.is_admin or expensive_check(user):
12    # If user.is_admin is True, expensive_check will NOT be called.
13    print("Access granted.")
14else:
15    print("Access denied.")
  • 早期終了を活用することで、処理の効率化や安全性の向上が可能になります。

and/orの優先順位

andor よりも優先されます。そのため、単純に組み合わせた条件式では、意図しない結果となる可能性があります。括弧を使って意図を明確にすることが重要です。

 1age = 15
 2is_student = True
 3
 4### Unclear example
 5# This is interpreted as: age > 18 and (age < 65 or is_student)
 6if age > 18 and age < 65 or is_student:
 7    pass
 8
 9### Clear example
10# Explicit parentheses make the intended logic obvious
11if (age > 18 and age < 65) or is_student:
12    pass
  • 括弧を使うことで、andor の優先順位を明確にでき、予期せぬバグを防ぎやすくなります。

TruthyとFalsyを理解する

Pythonでは、次の値がFalseと評価されます。

  • None
  • False
  • 数値の00.0を含む)
  • 空のシーケンス型(空のリストやタプル、空文字列など)
    • 例:[], (), ""
  • 空の辞書
    • 例:{}

これを活用すると、条件式を簡潔にできます。

1items = [1, 2, 3]
2
3### Bad Example
4if len(items) > 0:
5    pass
6
7### Good Example
8if items:
9    pass

elifelseの適切な使用

複数の条件を評価する場合、elifを使用します。最後にデフォルトの動作を定義するためにelseを使用します。

 1score = 80
 2
 3if score >= 90:
 4    grade = "A"
 5elif score >= 80:
 6    grade = "B"
 7elif score >= 70:
 8    grade = "C"
 9else:
10    grade = "F"
  • elseは必須ではありません。すべての条件を網羅する場合、省略可能です。
  • 条件式の順序に注意し、論理的に無駄のない並びにします。

ネストの深さを抑える

if文のネストが深くなると、コードが読みにくくなります。

 1def access_resource():
 2    return True
 3
 4### Bad Example
 5def deep_nest(user, resource):
 6    if user.is_authenticated:
 7        if user.has_permission:
 8            if resource.is_available:
 9                access_resource()
10
11### Good Example
12def early_return(user, resource):
13    if not user.is_authenticated:
14        return
15    if not user.has_permission:
16        return
17    if not resource.is_available:
18        return
19
20    access_resource()
  • 早期リターンを使用することで、ネストを減らしコードを簡潔にできます。

単一行のif文の使用を控える

単一行でif文を書くことが可能ですが、読みやすさが低下する場合があります。

 1condition = False
 2def do_something():
 3    return True
 4
 5### Bad Example
 6if condition: do_something()
 7
 8### Good Example
 9if condition:
10    do_something()
  • 短い条件式や動作に限り、単一行のif文を使用するのは許容されますが、冗長なコードは避けましょう。

三項演算子やorを使った単純化

単純な条件分岐の場合、三項演算子やorを使うことでコードを簡潔に記述できます。ただし、過度に詰め込み過ぎると読みにくくなるため、単純で直感的な条件だけを対象とします。

 1is_admin = True
 2input_name = None
 3
 4# Regular if statement
 5if is_admin:
 6    role = "Administrator"
 7else:
 8    role = "User"
 9
10# Simplified using an inline if
11role = "Administrator" if is_admin else "User"
12
13# Use 'or' to provide a default value
14name = input_name or "Guest"
  • シンプルな条件なら、三項演算子やorを使うことで、コードを短くわかりやすくできます。

条件式のキャッシュ

高コストな計算や関数呼び出しを含む条件式は、結果を変数にキャッシュして再利用することで、パフォーマンスを向上させます。

 1def expensive_function():
 2    pass
 3
 4def another_expensive_function():
 5    pass
 6
 7### Bad Example
 8if expensive_function() and another_expensive_function():
 9    pass
10
11### Good Example
12result1 = expensive_function()
13result2 = another_expensive_function()
14if result1 and result2:
15    pass

まとめ

Pythonのif文はシンプルで強力なツールですが、使い方によってはコードが複雑で読みにくくなる可能性があります。ここで紹介したベストプラクティスを取り入れることで、コードの可読性、保守性、効率性を向上させることができます。

YouTubeチャンネルでは、Visual Studio Codeを用いて上記の記事を見ながら確認できます。 ぜひYouTubeチャンネルもご覧ください。

YouTube Video