Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-确保修饰函数保留元数据_Python_Python Decorators - Fatal编程技术网

Python-确保修饰函数保留元数据

Python-确保修饰函数保留元数据,python,python-decorators,Python,Python Decorators,请告诉我是否有一种方法可以让修饰过的函数保留其元数据? 这将是装饰者的代码: def timer(func): """prints how long a function takes to run.""" def wrapper(*args, **kwargs): t_start = time.time() result = functionalists(*args, **kwargs) t_tota

请告诉我是否有一种方法可以让修饰过的函数保留其元数据? 这将是装饰者的代码:

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)
当我尝试用以下代码打印docstring时,元数据不会返回

print(sleep_n_seconds.__doc__)
请让我知道,如果我需要提供进一步的细节


谢谢

使用
functools
模块中的
wrapps
功能保留签名:

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

是否正在查找
functools.wrapps
?有关functools.wrapps的用法示例,请参阅(python3.4+部分)