brunch

You can make anything
by writing

C.S.Lewis

by 유윤식 Jun 11. 2024

Python: contextlib; with

#contextmanager #with #yield #ray

contextlib 의 contextmanager 를 사용하는 목적은

with 문장 안에서 커스텀 Function 을 사용하기 위함이다.


https://docs.python.org/ko/3/library/contextlib.html


보통 많이 사용하는 패턴이

with open('tmp/path/your/desti', 'w') as f:

    f.write("hello python!")


이러면 좋은점이 file 을 열고 닫는 내용을 직접 명시하지 않아도 된다.


ray 를 사용할 때에도 매번 Init() 함수를 호출하고,

끝날 때에는 shutdown() 함수를 꼭 호출해야 한다.


다른 예로는 pyspark 를 사용할 때인데

이때도 init() 과 close() 를 꼭 해줘야 한다.


그래서 이럴때 contextmanager 를 한 번 만들어두고 사용하면 편리할 것 같다는 생각이다.


간단하게 ray 를 예로 들면,


import ray

from contextlib import contextmanager


@contextmanager

def ray_cluster(**ray_init_args):

    _ = ray.init(**ray_init_args)

    try:

        yield ray

    finally:

        ray.shutdown()


@ray.remote

def hello_world():

    return "Hello, World!"


with ray_cluster(ignore_reinit_error=True) as ray:

    result = ray.get([hello_world.remote() for i in range(10)])

    print(result)


대략 이런 코드 모양이 아닐까 싶다.


@contextmanager 역할이 바로 ray_cluster 함수를 우리 잘 알고있는 open 함수와 비슷하게 만들어 준다.


공식문서를 한 번 천천히 읽어보면서 내 상황에 맞게끔 contextmanager 를 만들어 사용하면 될 듯.

작가의 이전글 Polars #06
작품 선택
키워드 선택 0 / 3 0
댓글여부
afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari