๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Language/Python

[Python] functools ์˜ partial | LIM

by forestlim 2022. 7. 9.
728x90
๋ฐ˜์‘ํ˜•

๐Ÿง functools ๋ชจ๋“ˆ์ด๋ž€?

functools ๋ชจ๋“ˆ์„ ๋ช‡ ๊ฐ€์ง€ ๊ณ ์œ„ ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ฉํ•œ๋‹ค. ๊ทธ ์ค‘ ๊ฐ€์žฅ ๋„๋ฆฌ ์•Œ๋ ค์ง„ ํ•จ์ˆ˜๊ฐ€ reduce() ํ•จ์ˆ˜์ด๋‹ค. functools์—์„œ ์ œ๊ณตํ•˜๋Š” ๋‚˜๋จธ์ง€ ํ•จ์ˆ˜ ์ค‘ partial() ๋ฐ ์ด์˜ ๋ณ€ํ˜•์ธ partialmethod() ํ•จ์ˆ˜๊ฐ€ ๋งค์šฐ ์œ ์šฉํ•˜๋‹ค๊ณ  ํ•œ๋‹ค. 

 

โœ”๏ธ run_in_executor ์— ์ด์šฉํ•œ functools.partial

functools.partial()์€ ํ•จ์ˆ˜๋ฅผ ๋ถ€๋ถ„์ ์œผ๋กœ ์‹คํ–‰ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ฃผ๋Š” ๊ณ ์œ„ํ•จ์ˆ˜์ด๋‹ค. ์–ด๋–ค ํ•จ์ˆ˜๊ฐ€ ์žˆ์„ ๋•Œ partial()์„ ์ ์šฉํ•˜๋ฉด ์›๋ž˜ ํ•จ์ˆ˜์˜ ์ผ๋ถ€ ์ธ์ˆ˜๋ฅผ ๊ณ ์ •ํ•œ ์ฝœ๋Ÿฌ๋ธ”์„ ์ƒ์„ฑํ•œ๋‹ค. ์ด ๊ธฐ๋ฒ•์€ ํ•˜๋‚˜ ์ด์ƒ์˜ ์ธ์ˆ˜๋ฅผ ๋ฐ›๋Š” ํ•จ์ˆ˜๋ฅผ ๊ทธ๋ณด๋‹ค ์ ์€ ์ธ์ˆ˜๋ฅผ ๋ฐ›๋Š” ์ฝœ๋ฐฑ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋Š” API์— ์‚ฌ์šฉํ•˜๊ณ ์ž ํ•  ๋•Œ ์œ ์šฉํ•˜๋‹ค. 

 

์˜ˆ๋ฅผ ๋“ค์–ด ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌํ•  ๋•Œ ๋„ค์ดํ‹ฐ๋ธŒ ์ฝ”๋ฃจํ‹ด ์•ˆ์—์„œ ๋ธ”๋กœํ‚น I/O ํ•จ์ˆ˜(requests.post)๋ฅผ ์‹คํ–‰ํ•˜๊ธฐ ์œ„ํ•ด ์ด๋ฒคํŠธ ๋ฃจํ”„์˜ run_in_executor๋ฅผ ์‚ฌ์šฉํ–ˆ๋Š”๋ฐ run_in_executor์˜ ํ•จ์ˆ˜๋Š” ์ด๋ ‡๊ฒŒ ์ƒ๊ฒผ๋‹ค.

 

run_in_executor๋Š” ๋น„๋™๊ธฐ๋ฅผ ๊ณ ๋ คํ•˜์ง€ ์•Š๊ณ  ๋งŒ๋“ค์–ด์ง„ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ๋น„๋™๊ธฐ๋กœ ์ด์šฉํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ค€๋‹ค.

 

def run_in_executor(self, executor, func, *args):
    self._check_closed()
    if self._debug:
        self._check_callback(func, 'run_in_executor')
    if executor is None:
        executor = self._default_executor
        # Only check when the default executor is being used
        self._check_default_executor()
        if executor is None:
            executor = concurrent.futures.ThreadPoolExecutor(
                thread_name_prefix='asyncio'
            )
            self._default_executor = executor
    return futures.wrap_future(
        executor.submit(func, *args), loop=self)

์ € func ์ธ์ž ์•ˆ์— requests.post(url, params=params) ๋ฅผ ์‹คํ–‰ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋„ฃ๊ณ  ์‹ถ์—ˆ๋‹ค. ์ด๋•Œ functools.partial()์„ ์‚ฌ์šฉํ–ˆ๋‹ค.

 

partial ํ•จ์ˆ˜๋Š” ๊ธฐ์กด ํ•จ์ˆ˜์™€ ๋™์ผํ•˜์ง€๋งŒ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๋ฏธ๋ฆฌ ์ •ํ•ด์ค€ ๋˜ ๋‹ค๋ฅธ ํ•จ์ˆ˜๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋œ๋‹ค.

 

๋”ฐ๋ผ์„œ ๋‚˜๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์‚ฌ์šฉํ–ˆ๋‹ค.

async def post_test(type, day):
    loop = asyncio.get_event_loop()
    await loop.run_in_executor(None, 
    	functools.partial(requests.post, url, params={'type': type, 'day': day}))

 

์ฆ‰ functools.partial์„ ์ด์šฉํ•ด์„œ

requests.post(url, params={'settlementType': settlementType, 'tradingDay': tradingDay})

์œ„์™€ ๊ฐ™์€ ๊ธฐ๋Šฅ์„ ์‹คํ–‰ํ•˜๊ฒŒ๋” ๋งŒ๋“  ๊ฒƒ์ด๋‹ค. 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€