저번 챕터에 만들었던 with 문을 클래스를 통해서 구현하는 것을 데코레이터를 사용해서 작업하는 방법에 대해서 알아보자.

# ex1
# user decorator

import contextlib
import time

@contextlib.contextmanager
def my_file_writer(file_name, method):
    f = open(file_name, method)
    yield f # __enter__ 암묵적
    f.close() # __exit__

with my_file_writer('testfile4.txt', 'w') as f:
    f.write('gogi banchang')

# ex2
# user decorator

@contextlib.contextmanager
def ExcuteTimerDc(msg):
    start = time.monotonic()
    try: # __enter__
        yield start
    except BaseException as e:
        print('Logging exception : {} : {} '.format(msg, e))
        raise
    else: # __exit__
        print('{} : {}  s'.format(msg, time.monotonic() - start))

with ExcuteTimerDc('start job!') as v:
    print('Received start monootionic2 : {}'.format(v))
    # Excute job.
    for i in range(40000000):
        pass
    raise ValueError('occured.')

데코레이터로 라이브러리를 가져와서 만들면 된다. 약간 웹 프레임워크 함수 기능이랑 클래스 기능 차이인거 같았다.