Posts /

With statement in python

08 May 2017



 # 파일작업, I/O, 리소스 획득 등등...
 some things up logic... 
  do something...
  # 닫기, 해제 등 무조건 실행되야 할 작업
  tear things down 
 # with문으로 교체
 class some_do:
  def __enter__(self):
   set things up...
   return thing
  def __exit__(self, type, value, traceback):
   tear things down

 with some_do() as thing:
   something do ... using thing

file로 구현되어 있는 예제

>>> f = open("x.txt")
>>> f
<open file 'x.txt', mode 'r' at 0x00AE82F0>

>>> f.__enter__() // file obj 자신을 return
<open file 'x.txt', mode 'r' at 0x00AE82F0>


>>> f.__exit__(None, None, None) // close

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file
with open("x.txt") as f:
    data =
    do something

Twitter Facebook Google+