Get the name of a decorated function?

RadiantHex picture RadiantHex · Feb 3, 2011 · Viewed 22.3k times · Source

here is my decorator:

def check_domain(func):

    def wrapper(domain_id, *args, **kwargs):
        domain = get_object_or_None(Domain, id=domain_id)
        if not domain:
            return None
        return func(domain_id, *args, **kwargs)

    return wrapper

Here is a wrapped up function:

@check_domain
def collect_data(domain_id, from_date, to_date):
    do_stuff(...)

If I do collect_data.__name__ I get wrapper instead of collect_data

Any ideas?

Answer

Zach Estela picture Zach Estela · Feb 7, 2017

functools.wraps is not needed! Just use func.__name__

import time

def timeit(func):
    def timed(*args, **kwargs):
        ts = time.time()
        result = func(*args, **kwargs)
        te = time.time()
        print('Function', func.__name__, 'time:', round((te -ts)*1000,1), 'ms')
        print()
        return result
    return timed

@timeit
def math_harder():
    [x**(x%17)^x%17 for x in range(1,5555)]
math_harder()

@timeit
def sleeper_agent():
    time.sleep(1)
sleeper_agent()

Outputs:

Function math_harder time: 8.4 ms
Function sleeper_agent time: 1003.7 ms