Python 速習チュートリアル

Python の Match 文 (Match Case)

1. Python Match Case 文

Python 3.10 で導入された match-case 文は、他の言語における「switch-case 文」に近い機能を提供しますが、より強力な構造的パターンマッチング(Structural Pattern Matching)を実現します。

match-case 文は、変数を評価し、その値が一つ以上の特定のパターンに一致するかどうかを検証します。

2. 基本的な構文

match キーワードに続けて変数(または式)を記述し、各 case ブロックでパターンを定義します。

def http_error(status):
    match status:
        case 400:
            return "不正なリクエスト (Bad request)"
        case 404:
            return "見つかりません (Not found)"
        case 418:
            return "私はティーポットです (I'm a teapot)"
        case _:
            return "その他のエラーが発生しました"

print(http_error(404))

3. デフォルトケース(ワイルドカード)

上記の例にある case _:ワイルドカード(Wildcard)と呼ばれ、他のどのケースにも一致しなかった場合に実行されるデフォルトの処理として機能します。これは従来の if-else 文における else ブロックに相当します。

match status:
    case 400:
        print("Bad Request")
    case _:
        print("不明なステータスコードです")

4. 複数の条件をまとめる

パイプ記号 |(OR 演算子)を使用することで、複数のパターンを一つの case ブロックにまとめることができます。

def check_status(status):
    match status:
        case 400 | 401 | 403:
            return "クライアントエラー"
        case 500 | 502:
            return "サーバーエラー"
        case _:
            return "正常、またはその他のエラー"

print(check_status(401))

5. ガード条件 (Case Guards)

case パターンの中に if 文を追加することで、パターンの一致にさらに詳細な条件(ガード条件)を付与することができます。

def check_value(x):
    match x:
        case n if n > 0:
            return f"{n} は正の数です"
        case n if n < 0:
            return f"{n} は負の数です"
        case 0:
            return "ゼロです"

print(check_value(-10))

このガード条件を利用することで、値の型や構造だけでなく、その値が特定の範囲内にあるかどうかといった動的な判定をパターンマッチングの中で完結させることが可能になります。