趣味のPython・深層学習

中級者のための実装集

デコレータ@contextmanagerを3stepで理解する。

ステップ1: try-finally を使用する例

まず、ファイルを開いて処理を行う際に、try-finally ブロックを使用する例を見てみましょう。これにより、ファイルが正しくクローズされることが保証されます。

Copy code
file_path: str = "example.txt"
try:
    file: TextIO = open(file_path, 'r')
    # ファイルの操作などを行う
finally:
    file.close()

ステップ2: クラスを使用した with ステートメント

次に、同じファイル操作をクラスを使って実現する例を見てみましょう。CustomFileHandler クラスは enterexit を実装し、ファイルのオープンとクローズを管理します。

from typing import TextIO

class CustomFileHandler:
    def __init__(self, file_path: str, mode: str):
        self.file_path: str = file_path
        self.mode: str = mode

    def __enter__(self) -> TextIO:
        self.file: TextIO = open(self.file_path, self.mode)
        return self.file

    def __exit__(self, exc_type, exc_value, traceback):
        self.file.close()

# 使用例
file_path: str = "example.txt"
with CustomFileHandler(file_path, 'r') as file:
    # ファイルの操作などを行う

ステップ3: @contextmanager を使用する例

最後に、@contextmanager デコレータを使って、もっと簡潔にコードを書く方法を見てみましょう。

from contextlib import contextmanager
from typing import TextIO

@contextmanager
def custom_file_handler(file_path: str, mode: str) -> TextIO:
    file: TextIO = open(file_path, mode)
    try:
        yield file
    finally:
        file.close()

# 使用例
file_path: str = "example.txt"
with custom_file_handler(file_path, 'r') as file:
    # ファイルの操作などを行う

これにより、with ステートメントでファイルのオープンとクローズが一元管理され、コードがより簡潔で理解しやすくなります。