Search This Blog

Loading...

Friday, February 22, 2013

Python decorators

They can by really helpful! A great explanation on how to create/use them can be found here, with some extra insights and helpful comments.
This is a decorator I created to log the time it takes to run an arbitrary function:

import time
import logging

logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)

# first, define the decorator
def time_log(function):
    def log_wrapper(*args, **kwargs):
        t0 = time.time()
        output = function(*args, **kwargs)
        elapsed = time.time() - t0
        if elapsed < 60:
            elapsed_str = '%.2f seconds' % (elapsed)
        else:
            elapsed_str = time.strftime('%H:%M:%S', time.gmtime(elapsed))
        logging.info('%s took %s' % (function.__name__, elapsed_str, ))
        return output
    return log_wrapper


# now you can use it:

# start by decorating a function
@time_log
def foo(N):
    import sys
    for i in range(N):
        sys.stdout.write("\r%d" % i)
        sys.stdout.flush()
        time.sleep(0.001)
    sys.stdout.write("\n")

# then use it as you'd normally do!
foo(1000)

No comments:

Post a Comment