contextlib
with문 컨텍스트를 위한 유틸리티
- 이 모듈은
with문이 수반되는 일반적인 작업을 위한 유틸리티를 제공
contextlib 모듈의 closing 활용
contextlib 모듈을 통해서 어떠한 작업을할때 자동으로 close 메소드를 호출하게끔 할 수 있음
class OpenClose:
def open(self):
print("작업을 시작합니다.")
def do_something(self):
print("작업을 진행합니다...")
print("작업을 진행합니다...")
print("작업을 진행합니다...")
def close(self):
print("작업을 종료합니다.")
def doOpenClose():
d = OpenClose()
d.open()
d.do_something()
d.close()
>>> from close import doOpenClose
>>> doOpenClose()
작업을 시작합니다.
작업을 진행합니다...
작업을 진행합니다...
작업을 진행합니다...
작업을 종료합니다.
>>>
- 명시적으로
OpenClose 클래스의 메소드들을 하나씩 호출
contextlib 모듈의 closing 메소드를 활용하면 자동으로 클래스 내부의 close 메소드를 호출하게 할 수 있음
contextlib 모듈의 closing 메소드를 import하고 doOpenClose() 메소드를 아래와 같이 수정
with절로 감싸며, closing 메소드를 사용했고, close() 메소드를 이번에는 사용하지 않았음
from contextlib import closing
... 생략 ...
def doOpenClose():
with closing(OpenClose()) as d :
d.open()
d.do_something()
>>> from close import doOpenClose
>>> doOpenClose()
작업을 시작합니다.
작업을 진행합니다...
작업을 진행합니다...
작업을 진행합니다...
작업을 종료합니다.
close 메소드를 실행하지 않았지만 closing 메소드가 클래스 내부의 close 메소드를 자동으로 실행해줌