1---2title: 'Python decorators'3date: '2007-08-16'4published_at: '2007-08-16T15:33:00.000+10:00'5tags: ['code', 'programming', 'python']6author: 'Gavin Jackson'7excerpt: 'I came across an interesting recent addition to the Python language (as of Python 2.4). They are called decorators. Decorators are Python objects that can register, annotate, and/or wrap a Python fun...'8updated_at: '2007-08-16T16:18:40.907+10:00'9legacy_url: 'http://www.gavinj.net/2007/08/python-decorators.html'10---1112I came across an interesting recent addition to the Python language (as of Python 2.4). They are called decorators. Decorators are Python objects that can register, annotate, and/or wrap a Python function or method. They are primarily used to achieve code reuse. This approach to programming struck me as being very similar to Aspect oriented programming. A decorator is a callable object (like a function) that accepts one argument—the function being decorated. The return value of the decorator replaces the original function definition. One use I found useful, was timing how long function calls actually take:1314```15import time1617def print_timing(func):1819 def wrapper(*arg):20 t1 = time.time()21 res = func(*arg)22 t2 = time.time()23 print '%s took %0.3f ms' % (func.func_name, (t2-t1)*1000.0)24 return res2526 return wrapper2728# declare the @ decorator just before the function, invokes print_timing()2930@print_timing31def myFunction(n):32```3334The following page discusses a number of other uses of this pattern (well worth a read). [http://www.phyast.pitt.edu/~micheles/python/documentation.html ](http://www.phyast.pitt.edu/%7Emicheles/python/documentation.html)353637