Python decorators Source

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---
11
12I 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:
13
14```
15import time
16
17def print_timing(func):
18
19  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 res
25
26  return wrapper
27
28# declare the @ decorator just before the function, invokes print_timing()
29
30@print_timing
31def myFunction(n):
32```
33
34The 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)
35
36
37