파이썬 컨텍스트 매니저

PythonBeginner
지금 연습하기

소개

이 랩에서는 파이썬 컨텍스트 매니저 (context manager) 의 힘을 활용하기 위한 여정을 떠나는 성간 여행자가 되어 마법 같은 밤하늘로 이동하게 됩니다. 이 매혹적인 시나리오에서 반짝이는 별과 천체의 경이로움을 탐험하면서 컨텍스트 관리의 심오한 미스터리를 탐구하게 됩니다.

컨텍스트 매니저 생성

이 단계에서는 일련의 작업을 캡슐화하기 위해 /home/labex/project/context_manager.py에서 파이썬 컨텍스트 매니저를 생성합니다. 다음은 성간 포털을 시뮬레이션하는 컨텍스트 매니저의 예시입니다.

class InterstellarPortal:
    def __enter__(self):
        print("Opening the portal to another dimension")

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Closing the portal")

## Example usage
with InterstellarPortal():
    print("Stepping into the interstellar portal")

스크립트를 실행합니다:

python context_manager.py

터미널에 다음 정보가 표시되어야 합니다:

Opening the portal to another dimension
Stepping into the interstellar portal
Closing the portal

컨텍스트 매니저 내 예외 처리

이 단계에서는 컨텍스트 내에서 발생할 수 있는 예외를 처리하도록 컨텍스트 매니저를 개선합니다. 수정된 InterstellarPortal 컨텍스트 매니저를 살펴보세요.

/home/labex/project/context_manager.py에서:

class InterstellarPortal:
    def __enter__(self):
        print("Opening the portal to another dimension")

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Closing the portal")
        if exc_type is not None:
            print(f"An error occurred: {exc_type}, {exc_val}")

## Example usage
with InterstellarPortal():
    print("Stepping into the interstellar portal")
    1 / 0  ## Simulate an error

스크립트를 실행합니다:

python context_manager.py

터미널에 다음 정보가 표시되어야 합니다:

Opening the portal to another dimension
Stepping into the interstellar portal
Closing the portal
An error occurred: <class 'ZeroDivisionError'>, division by zero
Traceback (most recent call last):
  File "/home/labex/project/context_manager.py", line 13, in <module>
    1 / 0  ## Simulate an error
ZeroDivisionError: division by zero

요약

이 랩에서는 자신만의 성간 포털 컨텍스트 매니저를 생성하고 예외를 우아하게 처리하도록 개선하여 파이썬 컨텍스트 매니저의 매혹적인 영역을 탐구했습니다. 이 여정을 통해 컨텍스트 관리의 신비로운 힘을 활용하고 파이썬의 우아한 기능에 대한 이해를 높일 수 있습니다. 즐거운 성간 코딩 되세요!