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

2
  • 4
    Are you looking for functools.wraps? Commented Jul 13, 2020 at 9:49
  • 1
    See Preserving signatures of decorated functions (The python3.4+ section) for example usage of functools.wraps Commented Jul 13, 2020 at 10:20

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.