현업 예시

Python으로 함수 작성하기

Shayne Miel

Software Architect @ Duo Security

함수 시간 측정

import time

def timer(func):
  """함수 실행에 걸린 시간을 출력하는 데코레이터.

  Args:
    func (callable): 데코레이션할 함수.

  Returns:
    callable: 데코레이션된 함수.
  """
Python으로 함수 작성하기
import time

def timer(func):
  """함수 실행에 걸린 시간을 출력하는 데코레이터."""

# 반환할 wrapper 함수를 정의합니다. def wrapper(*args, **kwargs):
# wrapper()가 호출될 때 현재 시간을 가져옵니다. t_start = time.time()
# 데코레이션된 함수를 호출하고 결과를 저장합니다. result = func(*args, **kwargs)
# 총 소요 시간을 구해 출력합니다. t_total = time.time() - t_start print('{} took {}s'.format(func.__name__, t_total))
return result
return wrapper
Python으로 함수 작성하기

timer() 사용

@timer
def sleep_n_seconds(n):
  time.sleep(n)
sleep_n_seconds(5)
sleep_n_seconds took 5.0050950050354s
sleep_n_seconds(10)
sleep_n_seconds took 10.010067701339722s
Python으로 함수 작성하기
def memoize(func):
  """데코레이션된 함수의 결과를 저장해 빠르게 조회합니다
  """

# 인자를 결과에 매핑하는 dict에 저장합니다 cache = {}
# 반환할 wrapper 함수를 정의합니다. def wrapper(*args, **kwargs): # 'kwargs'에 대한 해시 가능한 키를 정의합니다. kwargs_key = tuple(sorted(kwargs.items()))
# 이 인자를 처음 보면, if (args, kwargs_key) not in cache:
# func()을 호출하고 결과를 저장합니다. cache[(args, kwargs_key)] = func(*args, **kwargs)
return cache[(args, kwargs_key)]
return wrapper
Python으로 함수 작성하기
@memoize
def slow_function(a, b):
  print('Sleeping...')
  time.sleep(5)
  return a + b
slow_function(3, 4)
Sleeping...

7
slow_function(3, 4)
7
Python으로 함수 작성하기

데코레이터 사용 시점

  • 여러 함수에 공통 동작 추가
@timer
def foo():
  # do some computation

@timer
def bar():
  # do some other computation

@timer
def baz():
  # do something else
Python으로 함수 작성하기

연습해 봅시다!

Python으로 함수 작성하기

Preparing Video For Download...