Python | with 文が使える関数を作る

with 文が使える関数をつくる

yield 式のところで with ブロックの内容が実行される

#with_openthebook.py
from contextlib import contextmanager


class Book():
    def __init__(self):
        self.contents = ''
        self.isopen = False

    def open(self):
        self.isopen = True
        print('本は開かれた')
        return self

    def write(self, contents):
        if self.isopen:
            print('本に記録した')
            self.contents = contents
        else:
            print('本は開かれていない\n')

    def read(self):
        if self.isopen:
            print('本には次のように記録されていた')
            print(self.contents)
        else:
            print('本は開かれていない\n')

    def close(self):
        self.isopen = False
        print('本は閉じられた\n')


@contextmanager
def openthebook(book=None):
    if book is None:
        book = Book()
    book.open()
    try:
        yield book
    finally:
        book.close()


if __name__ == '__main__':
    with openthebook() as book:
        book.write('ばなな')
    book.read()
    with openthebook(book):
        book.read()

これを実行すると次のように表示される。

$ python with_openthebook.py
本は開かれた
本に記録した
本は閉じられた

本は開かれた
本には次のように記録されていた
ばなな
本は閉じられた

本は開かれていない