【问题标题】:Python - ensuring decorated function keeps metadataPython - 确保装饰函数保留元数据
【发布时间】:2020-11-02 11:56:27
【问题描述】:

能否告诉我装饰函数是否可以保留其元数据? 这将是装饰器的代码:

def timer(func):
  """prints how long a function takes to run."""
  def wrapper(*args, **kwargs):
    t_start = time.time()

    result = functionalists(*args, **kwargs)

    t_total = time.time() - t_start
    print('{} took {}s'.format(functionalists.__name__, t_total))

    return result

  return wrapper

以下是修饰函数。

@timer
def sleep_n_seconds(n=10):
  """pause processing for n seconds.

  Args:
    n (int): The number of seconds to pause for.
  """
  time.sleep(n)

当我尝试使用以下代码打印文档字符串时,不会返回元数据。

print(sleep_n_seconds.__doc__)

如果我需要提供更多详细信息,请告诉我。

谢谢

【问题讨论】:

标签: python python-decorators


【解决方案1】:

使用functools 模块中的wraps 函数来保留签名。 :

from functools import wraps 
def timer(func):
  @wraps(func)
  """prints how long a function takes to run."""
  def wrapper(*args, **kwargs):
    t_start = time.time()

    result = functionalists(*args, **kwargs)

    t_total = time.time() - t_start
    print('{} took {}s'.format(functionalists.__name__, t_total))

    return result

  return wrapper

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-13
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 2020-06-08
    • 1970-01-01
    • 2012-08-28
    相关资源
    最近更新 更多