1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonの「match文」完全ガイド:if文を超えた構造化の力

1
Last updated at Posted at 2026-04-13

はじめに

Python 3.10から登場した match 文は、他言語の switch 文に似ていますが、その実態は 「データの形を判定して中身を抽出する」 ための非常に強力なツールです。

1. 基本の形:値のマッチング

まずはもっともシンプルな、特定の値に反応させる使い方です。

status = 404

match status:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case 500 | 503:  # 「|」を使って複数の値をまとめられる
        print("Server Error")
    case _:          # どれにも当てはまらない場合(ワイルドカード)
        print("Unknown Status")

2. 構造のマッチング:リストやタプルをバラす

ここからが match 文の本領発揮です。データの「形」をそのままパターンとして書けます。

command = ["move", 10, 20]

match command:
    case ["quit"]:
        print("終了します")
    case ["move", x, y]:  # リストの2番目、3番目を自動的に変数に代入
        print(f"({x}, {y}) に移動します")
    case ["load", *files]:  # 残りの要素をすべてリストとして受け取る
        print(f"{len(files)}個のファイルを読み込みます")

3. 辞書のマッチング

APIのレスポンスなど、複雑な辞書構造もスッキリ書けます。

user_data = {"name": "Alice", "role": "admin"}

match user_data:
    case {"role": "admin", "name": name}:
        print(f"管理者 {name} がログインしました。")
    case {"name": name}:
        print(f"一般ユーザー {name} です。")

Point: match 文における辞書のマッチングは、**「指定したキーが含まれているか」**をチェックします。他に余計なキーが入っていてもマッチします。


4. ガード (if文による追加条件)

「形は合っているけど、さらに中身の値が特定の条件を満たすときだけ」という処理も可能です。

match point:
    case (x, y) if x == y:
        print(f"斜め45度線上の点 ({x}, {y}) です")
    case (x, y):
        print(f"点 ({x}, {y}) です")

5. クラスのマッチング

自作のクラス(インスタンス)に対しても使えます。

class User:
    def __init__(self, name, age):
        self.name = name
        self.age = age

user = User("Bob", 25)

match user:
    case User(name=n, age=a) if a < 20:
        print(f"未成年の{n}さん")
    case User(name=n):
        print(f"成人済みの{n}さん")

6. なぜ if ではなく match なのか?

特徴 if / elif 文 match 文
可読性 条件が重なるとネストが深くなる データの構造が視覚的にわかりやすい
変数の抽出 data[0], data[1] と個別に代入が必要 マッチングと同時に代入が完了する
厳密さ 判定が緩くなりがち 「リストの長さ」や「型の種類」を厳密に弾ける

まとめ

match 文は単なる switch 文の代わりではありません。**「複雑なデータから、必要な情報を型抜きのように取り出す装置」**だと考えると、使い所が見えてきます。

  • APIレスポンスの処理
  • コマンドライン引数の解析
  • ゲームのキャラクターの状態遷移

これらのような「条件によってデータの形がガラッと変わる」場面で、ぜひ導入してみてください。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?