Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorator makes functions return None

I built two functions to find prime factors. One version is slower than the other function on large number. I would like to evaluate the running time of those two functions. to do so I built a decorator to evaluate the time eclipsed. Since I plug the decorator my two functions return None. What is wrong in my code?

import math
import time

def time_usage(func):
    def wrapper(*args, **kwargs):
        beg_ts = time.time()
        func(*args, **kwargs)
        end_ts = time.time()
        print("[INFO] elapsed time: %f" % (end_ts - beg_ts))
    return wrapper

@time_usage
def find_factors(n):
    factors = []
    i = 2
    while i < n:
        while (n % i) == 0:
            factors.append(i)
            n /= i
        i += 1
    if n > 1:
        factors.append(n)
    return factors

@time_usage
def improved_prime_factor(n):
    factors = []
    # No need to test whether the number is divisible by any 
    # even number other than 2
    while n % 2 == 0:
        factors.append(2)
        n /= 2
    i = 3
    # If n = p * q, either p or q must be <= sqrt(n)
    max_factor = math.sqrt(n)
    while i <= max_factor:
        while n % i == 0:
            factors.append(i)
            n /= i
            # Update the upper band on possible factors
            max_factor = math.sqrt(n)
        i += 2
    if n > 1:
        factors.append(n)
    return factors

if __name__ == '__main__':
    print(improved_prime_factor(125556))  # return None
    print(find_factors(125556)) # return None
like image 622
Michael Avatar asked Dec 23 '22 22:12

Michael


1 Answers

You need to return func(*args, **kwargs). Also it is a good practice to decorate the wrapper method with functools.wraps

import functools


def time_usage(func):       
    @functools.wraps
    def wrapper(*args, **kwargs):
        beg_ts = time.time()
        result = func(*args, **kwargs)   # save the result to a name
        end_ts = time.time()
        print("[INFO] elapsed time: %f" % (end_ts - beg_ts))
        return result # return the name
    return wrapper
like image 145
styvane Avatar answered Jan 05 '23 02:01

styvane