Search This Blog


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)
            elapsed_str = time.strftime('%H:%M:%S', time.gmtime(elapsed))'%s took %s' % (function.__name__, elapsed_str, ))
        return output
    return log_wrapper

# now you can use it:

# start by decorating a function
def foo(N):
    import sys
    for i in range(N):
        sys.stdout.write("\r%d" % i)

# then use it as you'd normally do!

No comments:

Post a Comment