Python Woes: Decorators Lack Information
Python has a really cool feature called decorators. Which allow you to wrap functions around other functions in a clean way. The classic example would be the @trace decorator which would let us do this:
@trace def sayHello(name): print 'Hello %s!' % name
If we define the trace decorator like this:
from decorator import decorator @decorator def trace(func, *args, **kwargs): sig = func.__name__ print 'Entering:', sig func(*args, **kwargs) print 'Exiting:', sig @trace def sayHello(name): print 'Hello %s!' % name sayHello('Bob')
<<<< Output >>>>> Entering: sayHello Hello Bob! Exiting: sayHello
This uses the decorator module by Michele Simionato, which greatly simplifies writing many decorators by decorating the decorators!
Now decorators rock, but they have there limits. For that simple trace example it worked great, but lets move onto a much more complicated logging decorator. We would like to decorate functions with @log to indicate they should be log and that when logging is turned off nothing is printed. This lets us use print statements for debugging output and when logging is disabled nothing is printed out. The only problem is that decorators don't know what class the function they are decorating belongs to. So decorating a function with @log(True) to by default enable logging for that function doesn't work, because the decorator doesn't know the class that and function it should enable logging for.
Post new comment