운영체제의 입장은 리소스는 계속 소모를 하는데 반환되는 작업이 없으면 데이터를 많이 실행시킨다고 생각한다.

<aside> 💡 컨텍스트 매니저 : 원하는 타이밍 정확하게 리소스를 할당 및 제공, 반환하는 역할

</aside>

대표적으로 with 문을 이해해야한다. (문제 발생 요소 감소를 위해서)


# ex 1

file = open('./testfile1.txt', 'w')
# 옛날 형식, DB나 등등
try:
    file.write('Context Manager Test 1 \\n Contextlib Test1.')
finally:
    file.close()

# ex2

with open('./testfile2.txt', 'w') as f:
    f.write('Context Manager Test 2\\nContextlib Test1.')y

위는 대부분 언어에서 사용하는 기본 구문이다. 그러나 밑에 구문은 파이썬에서 제공하는 새로운 구문이다. (좋다 알아서 해준다.) 허나 with를 내가 입맛에 맞게 수정할 수 있다.

# ex3
# Use Class -> Context Manager with exception handling
class MyFileWriter():
    def __init__(self, file_name, method):
        print('MyFileWriter started : __init__')
        self.file_obj = open(file_name, method)

    def __enter__(self):
        print('MyFileWriter started : __enter__')
        return self.file_obj

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('MyFileWriter started : __exit__')
        if exc_type: #예외가 발생한 경우
            print('Logging exception {}'.format((exc_type, exc_val, exc_tb)))
        self.file_obj.close()

with MyFileWriter('./testfile2.txt', 'w') as f:
    f.write('Context Manager Test 3\\nContextlib Test1.')