0xf

日記だよ

with で関数をスコープの最後に呼ぶデコレータが作れる

デコレータで関数を返す以外のことができる、ということで試してみた。できる。使い道は...なんかある?

import sys

def closable(func):
    class _:
        def __enter__(self):
            print("enter")
            return self

        # exc_type は例外型、exc_value は例外に渡されたオブジェクトが含まれる
        def __exit__(self, exc_type, exc_value, traceback):
            func()
            print("exit", exc_type, exc_value, traceback)
    return _()

@closable
def scopeout():
    print("scopeout")

def main() -> None:
    with scopeout:
        print("hello")

if __name__ == "__main__":
    main()

出力結果はこれ。

enter
hello
scopeout
exit None None None

明示的にマジックメソッド持ちのクラスを書かなくていい、くらいの嬉しさではありそう。でも意外と嬉しいかも。