0

Is there a way to set all attributes in a decorated function as in the original function?

For example if I take this code:

def timeit(f):
    import time
    def new_f(n):
        start = time.time()
        res = f(n)
        end = time.time()
        tt = end-start
        print tt
        return res
    return new_f

@timeit
def fun(n=0):
    ''' docstring '''
    res = 0
    for _ in xrange(n):
        res = res + 1
    return res

Then the function fun has actually lost all its attributes such as fun.func_defaults or fun.func_dict or fun.func_doc. Is there a generic way to handle this?

othymomo
  • 105
  • 1
  • 2
  • 7
  • 1
    Quoting the accepted answer from the duplicated question: "That's why we have `functools.wraps`. This takes a function used in a decorator and adds the functionality of copying over the function name, docstring, arguments list, etc" – DeepSpace Feb 22 '18 at 13:12
  • Thanks - that is exactly what I was looking for. Too bad that it would be really hard to find the relevant question in SO without actually knowing the fuctools.wraps function... – othymomo Feb 22 '18 at 13:49

0 Answers0