デコレータとメタデータ

Python関数の書き方

Shayne Miel

Software Architect @ Duo Security

def sleep_n_seconds(n=10):
  """n 秒処理を一時停止します。

  Args:
    n (int): 停止する秒数。
  """
  time.sleep(n)

print(sleep_n_seconds.__doc__)
n 秒処理を一時停止します。

  Args:
    n (int): 停止する秒数。
Python関数の書き方
def sleep_n_seconds(n=10):
  """n 秒処理を一時停止します。

  Args:
    n (int): 停止する秒数。
  """
  time.sleep(n)

print(sleep_n_seconds.__name__)
sleep_n_seconds
print(sleep_n_seconds.__defaults__)
(10,)
Python関数の書き方
@timer
def sleep_n_seconds(n=10):
  """n 秒処理を一時停止します。

  Args:
    n (int): 停止する秒数。
  """
  time.sleep(n)

print(sleep_n_seconds.__doc__)


print(sleep_n_seconds.__name__)
wrapper
Python関数の書き方

timer デコレータ

def timer(func):
  """関数の実行時間を表示するデコレータ。"""

  def wrapper(*args, **kwargs):
    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関数の書き方
from functools import wraps

def timer(func): """関数の実行時間を表示するデコレータ。""" @wraps(func) def wrapper(*args, **kwargs):
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
def sleep_n_seconds(n=10):
  """n 秒処理を一時停止します。

  Args:
    n (int): 停止する秒数。
  """
  time.sleep(n)

print(sleep_n_seconds.__doc__)
n 秒処理を一時停止します。

  Args:
    n (int): 停止する秒数。
Python関数の書き方
@timer
def sleep_n_seconds(n=10):
  """n 秒処理を一時停止します。

  Args:
    n (int): 停止する秒数。
  """
  time.sleep(n)

print(sleep_n_seconds.__name__)
sleep_n_seconds
Python関数の書き方

元の関数へのアクセス

@timer
def sleep_n_seconds(n=10):
  """n 秒処理を一時停止します。

  Args:
    n (int): 停止する秒数。
  """
  time.sleep(n)

sleep_n_seconds.__wrapped__
<function sleep_n_seconds at 0x7f52cab44ae8>
Python関数の書き方

Passons à la pratique !

Python関数の書き方

Preparing Video For Download...