pythonpython-decorators

python annotation return result


How can I return the result of the annotation and the result of the function being executed? The code below only prints there result.

import time


def timeit(method):
    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()

        # print('%r (%r, %r) %2.2f sec' % \
        #     (method.__name__, args, kw, te - ts))
        print(te - ts)
        return result

    return timed


@timeit
def f1():
    time.sleep(1)
    return "abc"


result = f1()
print(type(result))

Solution

  • You can return a tuple (time_elapsed, function_result):

    import time
    
    
    def timeit(method):
        def timed(*args, **kw):
            ts = time.time()
            result = method(*args, **kw)
            te = time.time()
            elapsed = te - ts
            return elapsed, result
    
        return timed
    
    
    @timeit
    def f1():
        time.sleep(1)
        return "abc"
    
    
    result = f1()
    print(result)
    > (1.003918170928955, 'abc')
    
    elapsed, result = f1()
    print(elapsed)
    > 1.0018439292907715
    print(result)
    > abc