?

python with

지지리 2022. 11. 7. 23:02

/usr/lib/python3.8/_pyio.py

def open(file, mode="r", buffering=-1, encoding=None, errors=None,
         newline=None, closefd=True, opener=None):
        ...
        try:
            text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
            result = text
            text.mode = mode
            return result
        except:
            result.close()
            raise

class IOBase(metaclass=abc.ABCMeta):
    ...
    def __enter__(self):  # That's a forward reference
        """Context management protocol.  Returns self (an instance of IOBase)."""
        self._checkClosed()
        return self

    def __exit__(self, *args):
        """Context management protocol.  Calls close()"""
        self.close()

class TextIOBase(IOBase):
    ...

class TextIOWrapper(TextIOBase):
    ...

with 블록이 시작될 때 TextIOWrapper.__enter__() 실행

-> return self 에서 TextIOWrapper가 리턴됨

 

with 블록이 끝날 때 TextIOWrapper.__exit__() 실행

-> self.close() 때문에 파일이 닫힘

 

https://peps.python.org/pep-0343/

 

PEP 343 – The “with” Statement | peps.python.org

PEP 340, Anonymous Block Statements, combined many powerful ideas: using generators as block templates, adding exception handling and finalization to generators, and more. Besides praise it received a lot of opposition from people who didn’t like the fac

peps.python.org