seon99il

Python

Python의 with 문과 컨텍스트 매니저: try-finally의 우아한 대안

9분 소요

with open(...)을 아무 생각 없이 자주 쓰고 계실 것입니다. 하지만 with 블록을 벗어나는 순간 파일이 자동으로 닫히는 이유가 궁금했던 적은 없으신가요? 이 마법 같은 편리함은 사실 마법이 아니라 Python의 강력하고 우아한 디자인 패턴인 컨텍스트 관리 프로토콜(Context Management Protocol) 입니다.

이 글의 목표는 with 문을 단순히 사용하는 단계에서 어떻게 동작하는지 제대로 이해하는 단계로 나아가도록 돕는 것입니다. 글을 다 읽고 나면 직접 컨텍스트 매니저를 구현할 수 있고, 리소스 관리가 필요한 곳 어디에든 이 패턴을 자신 있게 적용할 수 있을 것입니다. try-finally의 번거로움을 느껴 보신 적이 있다면, 훨씬 더 나은 방법을 알게 되실 것입니다.

1. 들어가며: 익숙한 것을 의심해 보기

프로그래밍을 하다 보면 리소스를 획득하고, 사용하고, 안전하게 해제하는 패턴을 끊임없이 마주칩니다. 파일 핸들, 데이터베이스 커넥션, 네트워크 소켓, 스레드 락 등이 모두 여기에 해당합니다.

이를 처리하는 고전적인 방법은 try-finally 블록입니다.

# The classic try-finally approach
f = open('my_file.txt', 'w')
try:
    # Core logic that uses the file
    f.write('Hello, Python!')
    # What if an exception happens here?
    # raise ValueError("Something went wrong!")
finally:
    # Cleanup code that must always run
    print("Closing the file.")
    f.close()

이 코드는 안전합니다. try 블록에서 어떤 에러가 발생하더라도 finally 블록이 반드시 실행되어 파일이 닫힙니다. 하지만 분명한 단점이 있습니다.

  • 장황합니다: 단순한 파일 작업마다 try-finally 구조를 작성하는 것은 번거롭습니다.
  • 로직이 흩어집니다: 획득 코드(open)와 해제 코드(close)가 떨어져 있어 가독성을 해칠 수 있습니다.

with 문은 바로 이 문제를 해결하기 위해 설계되었습니다.

# The elegant 'with' statement
with open('my_file.txt', 'w') as f:
    # Core logic that uses the file
    f.write('Hello, Python!')
    # Even if an exception occurs here...
    # raise ValueError("Something went wrong!")

# The file is automatically closed upon exiting the block!
print("The file was closed automatically.")

코드가 훨씬 간결하고 직관적입니다. 리소스 관리는 with 문 자체에 맡기고, 우리는 핵심 로직에만 집중할 수 있습니다. 그렇다면 실제로는 어떻게 동작할까요?

2. 원리: with 문의 “프로토콜”

with 문은 마법이 아닙니다. 특정 프로토콜, 즉 컨텍스트 관리 프로토콜을 따르는 객체와 함께 동작할 뿐입니다. 이 프로토콜을 따르는 객체를 컨텍스트 매니저(Context Manager) 라고 부릅니다.

객체가 컨텍스트 매니저가 되려면 두 개의 특수 메서드 __enter__와 __exit__를 구현해야 합니다.

식당을 방문하는 상황에 비유해 보겠습니다.

  • __enter__: 식당에 들어가 자리를 안내받는 것과 같습니다. with 블록에 진입할 때 정확히 한 번 호출됩니다. 리소스 할당과 초기 설정 코드를 여기에 둡니다.
  • __exit__: 식사를 마치고 계산한 뒤 식당을 나서는 것과 같습니다. with 블록을 벗어날 때 어떤 이유로든(정상 종료든 예외든) 항상 호출됩니다. 리소스 정리(teardown) 코드를 여기에 두며, try-finally의 finally 절과 정확히 같은 역할을 합니다.

코드 블록의 실행 시간을 측정하는 간단한 Timer 컨텍스트 매니저를 만들어 동작을 확인해 보겠습니다.

import time

class Timer:
    def __init__(self):
        self.start_time = None

    def __enter__(self):
        print("Entering the restaurant. Starting the timer.")
        self.start_time = time.time()
        # The value returned here is assigned to the variable after 'as'
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        # These parameters are for exception handling (more on this soon!)
        end_time = time.time()
        elapsed = end_time - self.start_time
        print(f"Finished the meal. Total time: {elapsed:.4f} seconds")
        print("Leaving the restaurant and cleaning up.")
        # The return value of this method is also important.

# Using the Timer context manager
with Timer() as timer:
    print("\nEnjoying the meal...")
    time.sleep(1) # Pretend to do something for 1 second
    print(f"{time.time() - timer.start_time:.4f} seconds have passed since starting.\n")

# __exit__ is called automatically when the block is finished.

출력:

Entering the restaurant. Starting the timer.

Enjoying the meal...
1.0012 seconds have passed since starting.

Finished the meal. Total time: 1.0012 seconds
Leaving the restaurant and cleaning up.

보시다시피 with 블록에 들어갈 때 __enter__가, 나올 때 __exit__가 호출됩니다. __enter__가 self를 반환했기 때문에 as timer의 timer 변수에는 Timer 인스턴스가 담겼고, 블록 안에서 timer.start_time에 접근할 수 있었습니다.

3. 우아한 예외 처리의 비밀

여기서 컨텍스트 매니저의 진짜 깊이가 드러납니다. __exit__ 메서드는 왜 exc_type, exc_value, traceback이라는 세 개의 추가 매개변수를 가질까요? 이들은 with 블록 안에서 발생한 예외를 처리하기 위해 존재합니다.

  • 정상 종료 시: with 블록이 예외 없이 끝나면 세 매개변수 모두 None으로 전달됩니다.
  • 예외 종료 시: with 블록 안에서 예외가 발생하면 Python 인터프리터가 이를 잡아서, __exit__를 호출할 때 예외의 타입, 값, 트레이스백 정보를 세 매개변수로 전달합니다.

더 중요한 점은, __exit__의 반환값으로 예외의 전파 여부를 제어할 수 있다는 것입니다.

  • __exit__가 True를 반환하면: “이 예외는 내가 처리했으니 더 이상 던지지 마라”는 신호입니다. 예외는 억제(suppress) 됩니다.
  • __exit__가 False나 None(또는 참이 아닌 다른 값)을 반환하면: “이 예외는 처리하지 못했으니 평소처럼 전파하라”는 신호입니다. __exit__가 끝난 뒤 예외가 다시 발생(re-raise) 합니다.

한 가지 종류의 에러는 조용히 처리하고 나머지는 그대로 통과시키는 실용적인 예제를 살펴보겠습니다.

class ErrorHandler:
    def __enter__(self):
        print("Entering the critical zone.")
        return None # No need to return anything if you don't need an 'as' variable

    def __exit__(self, exc_type, exc_value, traceback):
        print("Exiting the critical zone.")
        if exc_type is ValueError:
            print(f"A ValueError occurred, but it's okay. I've handled it: {exc_value}")
            return True # Suppress the ValueError
        elif exc_type is not None:
            print(f"An unhandled error occurred ({exc_type.__name__})!")
            return False # Propagate all other exceptions

# Scenario 1: Handling a ValueError
print("--- Testing ValueError ---")
try:
    with ErrorHandler():
        print("Performing a value conversion...")
        raise ValueError("Invalid input provided.")
    print("Will this message be printed? (Yes, because the exception was suppressed)")
except ValueError:
    print("Will this message be printed? (No, because __exit__ handled it)")

print("\n" + "="*30 + "\n")

# Scenario 2: Handling a TypeError
print("--- Testing TypeError ---")
try:
    with ErrorHandler():
        print("Performing an operation...")
        result = '1' + 1
    print("This message will not be printed (because an exception occurred).")
except TypeError:
    print("The exception was propagated all the way out here, preventing a crash.")

출력:

--- Testing ValueError ---
Entering the critical zone.
Performing a value conversion...
Exiting the critical zone.
A ValueError occurred, but it's okay. I've handled it: Invalid input provided.
Will this message be printed? (Yes, because the exception was suppressed)

==============================

--- Testing TypeError ---
Entering the critical zone.
Performing an operation...
Exiting the critical zone.
An unhandled error occurred (TypeError)!
The exception was propagated all the way out here, preventing a crash.

__exit__를 활용하면 정리 로직과 에러 처리 로직을 컨텍스트 매니저 안에 깔끔하게 캡슐화할 수 있어, 더 깨끗하고 안전한 코드를 작성할 수 있습니다.

4. @contextlib.contextmanager로 더 간결하게

간단한 컨텍스트 매니저마다 클래스를 작성하는 것은 과하게 느껴질 수 있습니다. 다행히 Python 표준 라이브러리는 contextlib 모듈의 @contextmanager 데코레이터라는 더 우아한 해법을 제공합니다.

이 데코레이터를 사용하면 간단한 제너레이터 함수를 컨텍스트 매니저로 바꿀 수 있습니다.

  • 함수에 @contextlib.contextmanager를 붙입니다.
  • 함수 안에서 yield 키워드를 정확히 한 번 사용해야 합니다.
  • yield 이전의 코드: __enter__ 메서드 역할을 합니다.
  • yield된 값: as 변수에 할당되는 값이 됩니다.
  • yield 이후의 코드: __exit__ 메서드 역할을 합니다.

이를 견고하게 만드는 핵심은 yield 이후의 정리 코드가 항상 실행되도록 보장하는 것입니다. 가장 좋은 패턴은 제너레이터 안에서 yield를 try...finally 블록으로 감싸는 것입니다.

이 데코레이터로 Timer 클래스를 다시 작성해 보겠습니다.

from contextlib import contextmanager
import time

@contextmanager
def timer_func():
    # This part is the __enter__ logic
    print("Entering the restaurant (function version).")
    start_time = time.time()

    # Use try...finally for guaranteed cleanup
    try:
        # yield passes control back to the 'with' block
        yield start_time
    finally:
        # This part is the __exit__ logic
        end_time = time.time()
        elapsed = end_time - start_time
        print(f"Finished the meal. Total time: {elapsed:.4f} seconds (function version)")
        print("Leaving the restaurant and cleaning up (function version).")

# Using the decorator-based context manager
with timer_func() as start:
    print("\nEnjoying the meal... (function version)")
    time.sleep(1)
    print(f"{time.time() - start:.4f} seconds have passed since starting.\n")

클래스 버전과 비교해 보세요. 코드가 훨씬 간결하고, setup -> yield -> teardown의 흐름이 선형적이어서 더 직관적입니다. 대부분의 간단한 컨텍스트 매니저는 @contextmanager를 사용하는 것이 더 “Pythonic”한 방식입니다.

심화: Airflow 코드 속 자동 할당의 비밀

그렇다면 with 블록 안에서 dag=dag 인자를 생략했는데도 오퍼레이터는 어떻게 자신의 부모 DAG를 찾을까요? 비밀은 Airflow의 DAG 클래스와 모든 오퍼레이터의 부모인 BaseOperator 클래스가 DagContext라는 중간 관리자를 통해 영리하게 상호작용하는 데 있습니다.

1단계: DAG 클래스가 컨텍스트를 설정한다 (__enter__)

with DAG(...) 문이 실행되면 DAG 클래스의 __enter__ 메서드가 호출됩니다. 실제 Airflow 코드는 다음과 비슷한 구조입니다 (이해를 돕기 위해 단순화했습니다).

파일: airflow/models/dag.py

# The DAG class inherits from ContextManager
class DAG(LoggingMixin, DagOwnerAttributes, ContextManager['DAG']):
    ...
    def __enter__(self) -> Self:
        """
        Makes the DAG a context manager.
        Operators created within this context will be automatically assigned to this DAG.
        """
        # It tells a manager called DagContext, "I'm the active DAG now!"
        DagContext.push_context_managed_dag(self)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # When the block ends, it says, "I'm no longer the active DAG."
        DagContext.pop_context_managed_dag()

__enter__가 호출되면 DAG 객체(self)는 DagContext.push_context_managed_dag를 이용해 자신을 ‘현재 활성 DAG’ 로서 컨텍스트 스택에 푸시합니다. 식당에 들어가 테이블에 “현재 식사 중”이라는 표지판을 올려 두는 것과 같습니다.

2단계: BaseOperator가 컨텍스트를 확인한다 (__init__)

이제 with 블록 안에서 BashOperator 같은 오퍼레이터가 생성됩니다. 모든 오퍼레이터는 BaseOperator를 상속하며, BaseOperator의 생성자(__init__)에는 다음과 같은 핵심 로직이 들어 있습니다.

파일: airflow/models/baseoperator.py

# The parent class for all operators
class BaseOperator(TaskMixin, LoggingMixin):
    ...
    def __init__(
        self,
        *,
        dag: DAG | None = None, # The dag argument is optional
        ...
    ) -> None:
        ...
        # 1. It checks if the user passed a 'dag=...' argument directly.
        # 2. If not (if dag is None), it asks DagContext, "Is there an active DAG right now?"
        self.dag = dag or DagContext.get_context_managed_dag()

        if self.dag:
            # If it found an active DAG, it registers itself (the operator) with that DAG.
            self.dag.add_task(self)

이 코드가 마법의 핵심입니다. self.dag = dag or DagContext.get_context_managed_dag() 줄에 주목해 보세요. Python의 or 연산자를 영리하게 활용한 코드입니다.

  1. 사용자가 BashOperator(..., dag=my_dag)처럼 dag 인자를 명시적으로 전달하면 dag는 None이 아니므로 self.dag에는 my_dag가 할당됩니다.
  2. 하지만 with 블록에서처럼 dag 인자를 생략하면 dag는 None입니다. 그러면 or 표현식은 두 번째 부분인 DagContext.get_context_managed_dag()를 평가합니다.
  3. 이 함수는 DagContext 스택을 확인해, 방금 __enter__가 등록한 ‘현재 활성 DAG’ 를 가져옵니다.
  4. 결과적으로 self.dag에는 with 문에 쓰인 바로 그 DAG 객체가 할당되고, 오퍼레이터는 그 DAG에 자신을 추가합니다.

with 블록이 끝나면 DAG의 __exit__ 메서드가 호출되어 컨텍스트 스택에서 DAG를 제거합니다. 식당을 나설 때 테이블의 표지판을 치우는 것처럼 컨텍스트를 정리하는 것입니다.

이는 Airflow가 컨텍스트 매니저 프로토콜 같은 Python의 핵심 기능을 활용해, 개발자가 더 깔끔하고 오류가 적은 코드를 작성하도록 돕는 우아하고 직관적인 API를 제공하는 훌륭한 사례입니다.

코드를 업그레이드할 시간

이제 with 문이 단순한 문법적 편의(syntactic sugar) 이상이라는 것을 이해하셨을 것입니다. 컨텍스트 매니저와 함께 쓰이는 with 문은 뚜렷한 준비(setup) 단계와 정리(teardown) 단계가 있는 모든 작업을 안전하고 우아하게 다루는 강력한 디자인 패턴입니다.

파일에만 쓰는 것이 아닙니다. 이 패턴은 다음과 같은 곳에 적용할 수 있습니다.

  • 데이터베이스 커넥션 열기와 닫기
  • 스레드 락 획득과 해제
  • API 세션 시작과 종료
  • 설정을 일시적으로 바꿨다가 나중에 복원하기

여러분의 코드를 한번 살펴보세요. 반복되는 setup-teardown 또는 acquire-release 로직이 보이나요? 그렇다면 직접 만든 컨텍스트 매니저로 리팩터링해서 코드를 한 단계 끌어올릴 완벽한 기회입니다.

이전 글

전체 글 보기 →

댓글