본문 바로가기
프로그래밍언어/파이썬[중급]

[파이썬][중급] Chapter49. contextlib로 with문 확장하기

by about_IT 2025. 5. 25.
728x90

파이썬의 with 문은 파일 처리 외에도 리소스를 자동으로 열고 닫는 다양한 상황에서 활용됩니다. contextlib 모듈은 사용자 정의 context manager를 손쉽게 만들 수 있도록 도와주는 표준 라이브러리입니다.


● contextmanager로 간단히 정의

from contextlib import contextmanager

@contextmanager
def open_file(path):
    f = open(path, "r")
    try:
        yield f
    finally:
        f.close()

with open_file("sample.txt") as f:
    print(f.read())

try-finally 블록을 활용하여 리소스를 안전하게 관리할 수 있으며, yield 이전이 __enter__, 이후가 __exit__ 역할을 합니다.


● suppress로 예외 무시

from contextlib import suppress

with suppress(FileNotFoundError):
    open("no_file.txt")

suppress()는 특정 예외 발생을 무시하고 프로그램이 계속 진행되도록 합니다.


● redirect_stdout / redirect_stderr

from contextlib import redirect_stdout

with open("output.txt", "w") as f:
    with redirect_stdout(f):
        print("이 출력은 파일로 저장됩니다.")

출력을 파일이나 다른 객체로 리디렉션할 때 매우 유용합니다. redirect_stderr도 유사하게 사용됩니다.


● closing으로 종료 보장

from contextlib import closing
from urllib.request import urlopen

with closing(urlopen("http://example.com")) as page:
    print(page.read())

close() 메서드만 있는 객체도 with 문으로 안전하게 사용할 수 있도록 도와줍니다.


● ExitStack으로 복수 context 관리

from contextlib import ExitStack

with ExitStack() as stack:
    f1 = stack.enter_context(open("a.txt"))
    f2 = stack.enter_context(open("b.txt"))

복수 개의 리소스를 동적으로 관리해야 할 때 매우 유용한 방법입니다.


● 마무리

contextlib은 리소스 관리와 예외 처리를 우아하게 해결해주는 강력한 도구입니다. @contextmanager를 활용하면 클래스를 작성하지 않고도 커스텀 context manager를 간결하게 만들 수 있어, 다양한 상황에서 활용도가 높습니다.

728x90