[개발언어]/Python

with문에 대한 이해

_niel 2022. 10. 21. 16:03

파일 open에 주로 쓰는것으로 이해하고 있었으나 정확한 용도는

 

자원을 획득하고 사용 후 반납해야 하는 상황에 사용된다.

즉 객체의 라이프사이클(1.생성, 2.사용, 3.소멸)을 설계할 수 있다.

 

주로 I/O 바운드의 상황에 사용하게 된다

- 파일

- 외부서버와의 통신에 있어서의 세션유지

 

 

예시 1

class Hello:
    def __enter__(self):
        # 사용할 자원을 가져오거나 만든다(핸들러 등)
        print('enter...')
        return self # 반환값이 있어야 VARIABLE를 블록내에서 사용할 수 있다
        
    def sayHello(self, name):
        # 자원을 사용한다. ex) 인사한다
        print('hello ' + name)

    def __exit__(self, exc_type, exc_val, exc_tb):
        # 마지막 처리를 한다(자원반납 등)
        print('exit...')
        
with Hello() as h:
    h.sayHello('mom')
    h.sayHello('pap')
[result]
enter...
hello mom
hello pap
exit...

 

예시 2 (세션을 유지하고 닫을때)

import aiohttp
import asyncio


async def fetcher(session, url):
    async with session.get(url) as response:
        return await response.text()


async def main():
    urls = ["https://naver.com", "https://google.com", "https://instagram.com"] * 10

    async with aiohttp.ClientSession(
        connector=aiohttp.TCPConnector(ssl=False)
    ) as session:
        result = await asyncio.gather(*[fetcher(session, url) for url in urls])
        print(result)


if __name__ == "__main__":
    asyncio.run(main())

'[개발언어] > Python' 카테고리의 다른 글

GIL (Global Interpreter Lock)  (1) 2022.10.25
is와 == 의 차이  (0) 2022.10.25
파이썬 sorted 사용하기  (0) 2022.04.09
파이썬 문자열 처리  (0) 2022.04.08
파이썬 연산 정리  (0) 2022.04.06