Python

[Python] contextlib - Context Manager 관리

비번변경 2025. 2. 3. 12:30

개요 

2025.01.15-[Python] context manager - 리소스 관리에서 Context Manager라는 개념을 알아보고, Python 매직 메서드를 구현하는 방식으로 구현도 해봤다.

이번 글에서는 Context Manager를 구현하는 여러 가지 방법 중 contextlib를 활용하는 방법을 알아보려고 한다.

 

 

contextlib

contextlib은 Context Manager에 대한 일반적인 작업을 위한 유틸리티를 제공한다. 여러 작업을 할 수 있지만, contextmanger라는 데코레이터를 사용하면 매직 메서드를 구현하는 것보다 좀 더 간편하게 context manager를 구현할 수 있다.

contextmanger 데코레이터를 활용한 기본적인 구조는 아래와 같다.

from contextlib import contextmanager

@contextmanager
def func():
    __enter__
    yield
    __exit__

진입 시 처리할 일을 yield 키워드 이전에 정의하고 yield를 이용해 필요한 객체를 넘겨주었다가, 종료 시 처리할 일은 yield 이후에 정의한다. 사용할 때는 기존과 동일하게 with문에서 사용하면 된다.

제너레이터로 context manager를 구현하면 context manger를 위한 클래스를 직접 정의하지 않아도 될 뿐만 아니라 리팩토링이 쉬워질 수 있다.

 

 

예시

2025.01.15-[Python] context manager - 리소스 관리에서 구현했던 것과 같은 작업을 contextlib를 사용하여 구현해 보자.

 

아래 예시는 context manager 진입 시 리스트를 생성해 yield로 반환했다가, 종료 시 리스트의 원소를 출력하는 코드이다.

from contextlib import contextmanager

def manage_list():
    l = list()
    yield l
    print(l)
    
if __name__ == '__main__':
    with manage_list() as ml:
        ml.append(1)
        ml.append(2)

매직 메서드를 직접 구현했던 것과 동일하게 with문 내에서 print를 호출하지 않았음에도 리스트의 원소가 출력된 모습을 확인할 수 있다.

 

 

참고 문서

https://docs.python.org/ko/3/library/contextlib.html

https://good.oopy.io/clean-code/context-manager