Python の contextmanager 関数を返す関数の実験2022年12月16日 12時14分14秒

Python の contextmanager は処理後に後処理がある操作を実装するのに適している。ファイルの操作、ネットワーク、データベースの接続等、close する様な処理を簡単に実装できる。

この、contextmanager の機能を保持しつつ、追加で実装を追加出来るか実験。やりたいのは contextmanager 関数を返す事。簡単にした例を追った方が簡単だと思う。

from contextlib import contextmanager

@contextmanager
def session():
    print("before")
    yield session
    print("after")

def wrap():
    return session()

with session() as s:
    print("go")
print("=====")
with wrap() as w:
    print("try")
で、出力はこれ。
% python test_contextmanager.py 
before
go
after
=====
before
try
after
contextmanager の効果はしっかりと保持されたまま。