1

Could you please let me know if there is a way for a decorated function to keep its metadata? This would be the code for the decorator:

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

The following would be the decorated function.

@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)

When I try to print the docstrings with the following code, the metadata is not returned.

print(sleep_n_seconds.__doc__)

Please let me know if I need to provide further details.

Thank you

Michele Giglioni
  • 329
  • 4
  • 15

1 Answers1

2

Use the wraps function from functools module to retain the signature. :

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
Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40