[Python] With 구문 + Context Manager

JinUk Lee·2023년 12월 21일

python 개념 공부

목록 보기
3/14

with 는 파이썬에서 파일처리를 하는 기능이다.

보통 프로그램에서 파일을 처리할때

열기 (open) - 연산 - 닫기 (close) 의 과정을 거친다.

파일을 열고 연산한 뒤에는 다른 프로세스를 위해 반드시 닫아야하는데, 이 과정에서 오류가 발생할 수 있다.

with는 이러한 오류를 방지하기위한 구문으로 with절을 탈출하면 반드시 close 하기 때문에 오류 방지가 가능하다.

사용법

# 기존
f = open('test.txt', 'r')
sen = f.readline()
f.close()

# with 문법
with open('test.txt', 'w') as f:
	f.write('test')

Context Manager

__enter__() , __exit__() 두 메서드를 활용하여 with 구문의 활용도를 높일 수 있다.

두 구문은 각각 with 구문이 시작될때, 끝날 때 실행된다.


class Hello:
    def __enter__(self):
        print('enter...')
        return self 
        
    def sayHello(self, name):
        print('hello ' + name)

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('exit...')

with Hello() as h:
    h.sayHello("name")
    
# 출력 결과
enter...
hello name
exit...
profile
개발자 지망생

0개의 댓글