以前、仕事でデータベースのトランザクションを管理する Python の API を考えているときに、同僚と「デコレータで作るべき」「いやコンテキストマネージャの方が扱いやすい」みたいなやり取りをしたことがあった。 でも、今考えるとどちらとしても動作するように作っておけばよかったんだよね。 ということで、今回はデコレータとしても動作するしコンテキストマネージャとしても動作するような API を作る方法について書くことにする。 補足しておくと、デコレータもコンテキストマネージャも対象となる処理の前後に特定の処理を挿入できるというところに共通点がある。 今回紹介する内容も、対象となる処理の前後に特定の処理を挿入するというものになっている。 サンプルコードその一 以下のサンプルコードでは、clamp() 関数がデコレータとしてもコンテキストマネージャとしても動作するように作られている。 clamp