카테고리 없음

스파르타 AI-8기 TIL(1/31)-TeamProject

kimjunki-8 2025. 1. 31. 23:00
컨텍스트 매니저(Context Managers)
컨텍스트 매니저는 리소스를 자동으로 관리하는 기능을 제공하는 파이썬의 강력한 개념이에요.
주로 with 문과 함께 사용되며, 리소스의 획득과 해제를 자동으로 처리하여 코드의 안정성을 높여줍니다.
컨텍스트 매니저의 핵심 기능
리소스 관리: 파일, 데이터베이스 연결, 네트워크 소켓 등의 리소스를 안전하게 다룸
자동 해제: 예외가 발생하더라도 리소스를 깔끔하게 정리
가독성 향상: try-finally보다 간결한 코드 작성 가능

컨텍스트 매니저의 주요 함수와 전체적인 구조
파일 처리 관련 함수 (open, write, read, close)
with open("example.txt", "w") as file:  # 파일을 쓰기 모드("w")로 열기
    file.write("Hello, Context Manager!")  # 파일에 내용 쓰기
# 파일이 자동으로 닫힘


컨텍스트 매니저 없이 리소스 관리하기 (비효율적인 방법)

file = open("example.txt", "w")
try:
    file.write("Hello, World!")
finally:
    file.close()  # 파일 닫기

finally를 사용해 파일을 닫아야 하는데, 코드가 길어지고 실수로 close()를 빼먹으면 메모리 누수가 발생할 수 있습니다.

컨텍스트 매니저를 사용한 리소스 관리 (깔끔한 방법)

with open("example.txt", "w") as file:
    file.write("Hello, World!")  # 자동으로 파일이 닫힘

with 블록이 끝나면 자동으로 file.close()가 호출됩니다.
예외가 발생해도 자동으로 리소스가 해제됩니다.

컨텍스트 매니저의 동작 원리
컨텍스트 매니저는 __enter__()와 __exit__()라는 두 개의 특별한 메서드로 이루어져 있어요.
이 메서드가 자동으로 호출되면서 리소스가 생성되고 해제되는 구조입니다.

class MyContext:
    def __enter__(self):
        print("Entering context...")
        return self  # 필요한 리소스를 반환할 수도 있음

    def __exit__(self, exc_type, exc_value, traceback):
        print("Exiting context...")
        # 예외가 발생하면 처리할 수도 있음

with MyContext():
    print("Inside the context block!")
    
결과:
Entering context...
Inside the context block!
Exiting context...

__enter__()가 실행된 후 with 블록이 실행됨.
with 블록이 끝나면 __exit__()가 실행됨 (예외가 발생하든 안 하든).

컨텍스트 매니저를 직접 구현하기

class FileManager:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
        self.file = None

    def __enter__(self):
        print(f"Opening file: {self.filename}")
        self.file = open(self.filename, self.mode)
        return self.file  # 파일 객체 반환

    def __exit__(self, exc_type, exc_value, traceback):
        print(f"Closing file: {self.filename}")
        if self.file:
            self.file.close()

# 사용 예시
with FileManager("test.txt", "w") as f:
    f.write("Hello, Context Manager!")

with 블록이 끝나면 자동으로 __exit__()가 호출되어 파일이 닫혀요.

contextlib을 활용한 컨텍스트 매니저 만들기
@contextmanager 데코레이터 사용

from contextlib import contextmanager

@contextmanager
def file_manager(filename, mode):
    print(f"Opening file: {filename}")
    file = open(filename, mode)
    try:
        yield file  # 리소스를 반환하고 블록 실행
    finally:
        print(f"Closing file: {filename}")
        file.close()

# 사용 예시
with file_manager("test.txt", "w") as f:
    f.write("Hello, World!")

yield 이전 코드가 __enter__() 역할,
yield 이후 코드가 __exit__() 역할을 함.
try-finally 구조를 사용해 예외가 발생해도 파일이 닫힘.

오늘도 여기까지.