Pythonのコンテキストマネージャーとは?withの使い方

Pythonのコンテキストマネージャー とは with を使った構文で、リソースの解放や後処理を自動でやってくれる仕組みです。

基本構文

with コンテキストマネージャ as 変数:
    処理

ファイル操作の例

通常は f = open(...) と書いたら f.close() を忘れないようにする必要があるが、with を使えば自動でクリーンアップされる

with open("data.txt", "r") as f:
    content = f.read()
    print(content)

# withブロックを抜けると、自動でf.close()が呼ばれる

複数のリソースをまとめる

with open("input.txt") as fin, open("output.txt", "w") as fout:
    for line in fin:
        fout.write(line.upper())

try-finally との違い

withはこれと同じことを簡潔に書ける

f = open("data.txt")
try:
    content = f.read()
finally:
    f.close()

自作コンテキストマネージャ

with で使えるオブジェクトは、コンテキストマネージャ という仕組みを実装している必要がある
具体的には __enter____exit__ メソッドを持つクラスのこと

class MyResource:
    def __enter__(self):
        print("リソース確保")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print("リソース解放")

with MyResource() as r:
    print("処理中")

# 出力:
# リソース確保
# 処理中
# リソース解放

まとめ

  • with 文はリソース管理(ファイル、DB接続、ロック処理など)に便利
  • 自動でクリーンアップを実行してくれる → try-finallyを簡潔に書ける
  • 自作する場合は __enter__ / __exit__ を実装したクラスを作ればよい

実務では ファイル操作、データベース接続、スレッドロック、外部リソース確保 などで頻繁に使います。

-Python