• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

파이썬 lv3 의 py_ad_4_2.py 에서 Image를 열기만 하고 닫지는 않으셨습니다.

23.06.02 08:34 작성 조회수 222

0

메모리 누수가 일어날 것 같은데 코드 수정 부탁드립니다.
with 문을 써서 구현해야될 것 같은데 어떻게 수정해야될까요?

 

  • 문제되는 코드

img, *images = [Image.open(f) for f in sorted(glob.glob(path_in))] # open 만 하고 닫지는 않음.

답변 1

답변을 작성해보세요.

0

안녕하세요.

좋은 질문 감사합니다. 결론적으로 메모리 누수에 대해 크게 걱정하실 필요는 없습니다.

하지만 실제 서비스를 염두해둔 코딩이라면 말씀하신대로 정확하게 with문(컨텍스트) 등으로 자원을 회수해야해요.

위에코드에서는 파일을 닫는 타이밍이 내부 가비지 컬렉션에 따라 작동합니다.(딜레이)

또한, cpython에서는 즉시 close문이 동작해서 문제가 되지 않습니다.

실제 코드에서는 해당 코드와 같이 사용하는 것 보다는 정석으로 with 구문으로 사용을 추천드립니다.

아래는 해당 원문입니다.

t should close the file, yes, though when exactly it does so is implementation-dependent. The reason is that there is no reference to the open file after the end of the list comprehension, so it will be garbage collected, and that will close the file.

In CPython (the regular interpreter version from python.org), it will happen immediately, since its garbage collector works by reference counting. In another interpreter, like Jython or Iron Python, there may be a delay.

If you want to be sure your file gets closed, it's much better to use a with statement: