with statement 사용 -> 리소스 관리를 좀더 안전하고 명확하게 할 수 있음
ex) file IO
file_handle = open(path_to_file, 'r')
for line in file_handle.readlines():
if raise_exception(line):
print('Exception!')
만약 if raise_exception(line)
에서 에러가 발생하면, 에러를 따로 잡는 코드가 없기 때문에, 코드는 종료되지만, 오픈된 파일을 close할 수가 없다.
with open(path_to_file, 'r') as file_handle:
for line in file_handle:
if raise_exception(line):
print('Exception!')
context manager 구현 방법:
많은 표준 라이브러리에서 제공
__enter, __exit 메소드 정의
class controlled_execution:
def __enter__(self):
set things up
return thing
def __exit__(self, type, value, traceback):
tear things down
with controlled_execution() as thing:
some code using thing
https://valuefactory.tistory.com/514
from contextlib import contextmanager
@contextmanager
def managed_resource(*args, **kwds):
# Code to acquire resource, e.g.:
resource = acquire_resource(*args, **kwds)
try:
yield resource
finally:
# Code to release resource, e.g.:
release_resource(resource)
>>> with managed_resource(timeout=3600) as resource:
... # Resource is released at the end of this block,
... # even if code in the block raises an exception