Python @contextmanagerの使い方|from contextlib import contextmanagerでwith文を作る(yield・try/finally・よくあるエラー)
@contextmanagerは、from contextlib import contextmanager で読み込んで関数に付けると、その関数をwith文で使えるようにするデコレータです。関数の中に yield を1回だけ書き、yieldの前がwithに入るときの処理、後ろがwithを抜けるときの処理になります。後始末を確実に実行するには、yieldを try / finally で囲みます。
この記事では、基本の書き方、as で値を渡す方法、例外が起きたときの動き、よく出るエラー(yieldの書き忘れ・2回書いた・2回使った)、デコレータとしての使い方、型ヒントの書き方、非同期版の @asynccontextmanager までを、実際に動かした結果つきで説明します。コードはPython 3.14.8で実行しました(2026年10月18日確認)。contextlib全体の概要は「Python contextlibとは?」、クラスで書く方法は「Python __enter__・__exit__とは?」で扱っています。
@contextmanagerの基本の書き方
from contextlib import contextmanager
@contextmanager
def tag(name):
print(f"<{name}>")
yield
print(f"</{name}>")
with tag("p"):
print(" 本文")
実行結果:
<p>
本文
</p>
| 関数の中の位置 | 実行されるタイミング |
|---|---|
yield の前 |
withブロックに入るとき |
yield そのもの |
ここで止まり、withブロックの中身が実行される |
yield の後ろ |
withブロックを抜けるとき |
yield x の x |
with ... as 変数 の変数に入る値 |
yieldを含む関数はジェネレータ関数です。@contextmanagerは、そのジェネレータを「入るときに1回進め、抜けるときにもう1回進める」ことでwith文の動きを作っています。ジェネレータの仕組みは「Pythonのイテレータとジェネレータとは?」で解説しています。
asで値を受け取る
from contextlib import contextmanager
@contextmanager
def opened(path, mode="w"):
f = open(path, mode, encoding="utf-8")
try:
yield f
finally:
f.close()
print("closeした")
with opened("t.txt") as f:
f.write("hello")
with open("t.txt", encoding="utf-8") as f:
print("中身:", f.read())
実行結果:
closeした
中身: hello
yield f の f が、as f の変数に入ります。値を渡す必要がなければ yield だけで構いません。なお、ファイルは組み込みの open() がもともとwith文に対応しているので、実際のコードではこの関数を作る必要はありません(ここでは仕組みの説明のための例です)。
try/finallyで囲まないと後始末が飛ばされる
withブロックの中で例外が起きると、その例外は yield の位置で関数の中に送り込まれます。tryで囲んでいないと、yieldの後ろの行は実行されません。
from contextlib import contextmanager
@contextmanager
def bad():
print("開始")
yield
print("終了")
@contextmanager
def good():
print("開始")
try:
yield
finally:
print("終了(必ず実行)")
for cm in (bad, good):
try:
with cm():
raise ValueError("x")
except ValueError:
print(f"{cm.__name__}: ValueErrorを外で受け取った")
実行結果:
開始
bad: ValueErrorを外で受け取った
開始
終了(必ず実行)
good: ValueErrorを外で受け取った
bad() では「終了」が表示されていません。ファイルを閉じる、ロックを外す、設定を元に戻すといった後始末は、必ず finally に書きます。公式ドキュメントの例も、yieldを try / finally で囲む形になっています(contextlib — contextmanager、Python 3.15.0版、2026年10月18日確認)。
例外を中で受け取って止める
from contextlib import contextmanager
@contextmanager
def catch():
try:
yield
except ValueError as e:
print("中で捕捉:", e)
with catch():
raise ValueError("握りつぶす")
print("続行できた")
中で捕捉: 握りつぶす
続行できた
except で受け取って再送出しなければ、例外はwithの外に出ません。クラスで書いた場合に __exit__ が True を返すのと同じ効果です。ただし、意図せず握りつぶすとエラーが見えなくなります。決まった例外を無視したいだけなら、専用の contextlib.suppress() を使うほうが読み手に意図が伝わります(「Python contextlib.suppress()とは?」)。
よく出るエラー3つ
from contextlib import contextmanager
@contextmanager
def no_yield():
print("yieldを書き忘れた")
@contextmanager
def twice():
yield
yield
for cm in (no_yield, twice):
try:
with cm():
pass
except Exception as e:
print(f"{cm.__name__}: {type(e).__name__}: {e}")
@contextmanager
def once():
yield
cm = once()
with cm:
pass
with cm: # 同じオブジェクトを2回使う
pass
実行結果:
yieldを書き忘れた
no_yield: TypeError: 'NoneType' object is not an iterator
twice: RuntimeError: generator didn't stop
AttributeError: '_GeneratorContextManager' object has no attribute 'args'
| エラー | 原因 | 直し方 |
|---|---|---|
TypeError: 'NoneType' object is not an iterator |
yieldが無く、ただの関数になっている | yieldを1回書く |
RuntimeError: generator didn't stop |
yieldが2回以上実行された | yieldをちょうど1回にする(ループの中に置かない) |
RuntimeError: generator didn't yield |
yieldの前で関数が終わった(条件分岐でyieldを通らなかった等) | どの経路でも1回yieldを通るようにする |
2回目のwithで AttributeError |
作ったオブジェクトを使い回した | 使うたびに once() を呼び直す |
最後のエラーは、ジェネレータが1回目で使い切られているためです。公式ドキュメントでも、@contextmanagerで作ったものは「1回きり(single use)」と説明されています。エラーの文面はPythonのバージョンで変わることがありますが、2回目が失敗する点は同じです。
デコレータとしても使える
@contextmanagerで作った関数は、with文だけでなく、別の関数のデコレータとしても使えます。関数を呼ぶたびに新しく作り直されるので、何回呼んでも上の「1回きり」のエラーにはなりません(公式ドキュメントの contextmanager の項、2026年10月18日確認)。
from contextlib import contextmanager
import time
@contextmanager
def timer(label):
start = time.perf_counter()
try:
yield
finally:
print(f"{label}: {time.perf_counter() - start:.3f}秒")
with timer("集計"):
sum(range(1_000_000))
@timer("関数全体")
def work():
return sum(range(2_000_000))
work()
work()
実行結果(秒数は環境によって変わります):
集計: 0.007秒
関数全体: 0.014秒
関数全体: 0.014秒
処理時間の測り方は「Python time.perf_counter()とは?」で詳しく解説しています。
実践例:設定を一時的に変えて必ず戻す
from contextlib import contextmanager
settings = {"debug": False}
@contextmanager
def override(key, value):
old = settings[key]
settings[key] = value
try:
yield
finally:
settings[key] = old
print(settings)
with override("debug", True):
print(settings)
print(settings)
{'debug': False}
{'debug': True}
{'debug': False}
「状態を変えて、終わったら必ず戻す」形は@contextmanagerの典型的な使い方です。途中で例外が起きても、finallyで元の値に戻ります。
作業フォルダの一時変更は contextlib.chdir がある
作業フォルダを一時的に移る処理は、自分で書かなくても Python 3.11 から contextlib.chdir() が用意されています(公式ドキュメント「Added in version 3.11」、2026年10月18日確認)。
import os
import tempfile
from contextlib import chdir
before = os.getcwd()
with tempfile.TemporaryDirectory() as d:
with chdir(d):
print("中:", os.getcwd() != before)
print("後:", os.getcwd() == before)
中: True
後: True
標準ライブラリにすでにあるものは、それを使うほうが安全です。closeを確実に呼ぶ closing()、複数の後始末をまとめる ExitStack も contextlib にあります。
型ヒントの書き方
@contextmanagerを付ける関数はジェネレータ関数なので、戻り値の型は Iterator[yieldする値の型] と書きます(Generator[str, None, None] でも同じ意味です)。
from collections.abc import Iterator
from contextlib import contextmanager
@contextmanager
def config(value: str) -> Iterator[str]:
yield value.upper()
with config("debug") as v:
print(v)
DEBUG
何もyieldしないなら Iterator[None] です。
非同期版の@asynccontextmanager
async with で使うものを作るときは、@asynccontextmanager を async def の関数に付けます。書き方は同じです。
import asyncio
from contextlib import asynccontextmanager
@asynccontextmanager
async def connect(name):
print(f"{name}に接続")
try:
yield name
finally:
print(f"{name}を切断")
async def main():
async with connect("DB") as conn:
print("使用中:", conn)
asyncio.run(main())
DBに接続
使用中: DB
DBを切断
クラスで書く場合との使い分け
| 項目 | @contextmanager | クラス(__enter__ / __exit__) |
|---|---|---|
| コード量 | 少ない | 多い |
| 読み方 | 上から下へ順に読める | 2つのメソッドに分かれる |
| 同じオブジェクトの使い回し | できない(毎回呼び直す) | 作り方しだいでできる |
| with以外のメソッドも持たせる | できない | できる |
ほとんどの場面は@contextmanagerで足ります。同じオブジェクトを何度もwithに入れたいときや、withの外でもメソッドを呼びたいときはクラスで書きます。
よくある質問
Q. from contextlib import contextmanager は何をしていますか。
標準ライブラリ contextlib から contextmanager というデコレータを読み込んでいます。インストールは不要で、関数に @contextmanager を付けると、その関数を with 文で使えるようになります。
Q. yieldは何回書けばいいですか。
ちょうど1回です。yieldが無いと TypeError、2回以上実行されると RuntimeError: generator didn’t stop になります。
Q. withの中で例外が起きたら後始末はされますか。
yield を try / finally で囲んでいれば、finally の中の処理は必ず実行されます。囲んでいないと、yield より後ろの行は実行されません。
Q. 同じものを2回withで使うとエラーになります。
@contextmanager で作ったものは1回きりです。使うたびに関数を呼び直して新しく作ってください。デコレータとして使う場合は呼び出しごとに作り直されるので問題ありません。
まとめ
from contextlib import contextmanagerを付けた関数は、with文で使える- yieldの前が入るとき、後ろが抜けるとき。yieldはちょうど1回
- 後始末は
try/finallyの finally に書く - 作ったものは1回きり。デコレータとして使えば呼ぶたびに作り直される
- 型ヒントは
Iterator[値の型]、非同期なら@asynccontextmanager chdir・suppress・closingなど、contextlibに既製品があればそれを使う





