Why use decorators?
The usual method for transforming functions and methods (for instance, declaring them as a class or static method) is awkward and can lead to code that is difficult to understand. Ideally, these transformations should be made at the same point in the code where the declaration itself is made.
The winning syntax as of now uses the '@' symbol, as described in this message. Mark Russell implemented this version. Here is the message describing the patch he checked in.
There has been a long discussion about the syntax to use for decorators in Python.
Toggle line numbers
- Code: Select all
3 def foo (arg1, arg2):
Python Decorator Samples:
- Code: Select all
1 def simple_decorator(decorator):
2 """This decorator can be used to turn simple functions
3 into well-behaved decorators, so long as the decorators
4 are fairly simple. If a decorator expects a function and
5 returns a function (no descriptors), and if it doesn't
6 modify function attributes or docstring, then it is
7 eligible to use this. Simply apply @simple_decorator to
8 your decorator and it will automatically preserve the
9 docstring and function attributes of functions to which
10 it is applied."""
11 def new_decorator(f):
12 g = decorator(f)
13 g.__name__ = f.__name__
14 g.__doc__ = f.__doc__
16 return g
17 # Now a few lines needed to make simple_decorator itself
18 # be a well-behaved decorator.
19 new_decorator.__name__ = decorator.__name__
20 new_decorator.__doc__ = decorator.__doc__
22 return new_decorator
25 # Sample Use:
28 def mySimpleLoggingDecorator( func ):
29 def YOU_WILL_NEVER_SEE_THIS_NAME( *args, **kwargs ):
30 print 'calling %s' % func.__name__
31 return func( *args, **kwargs )
32 return YOU_WILL_NEVER_SEE_THIS_NAME
35 def double(x):
36 "Doubles a number"
37 return 2*x
39 assert double.__name__ == 'double'
40 assert double.__doc__ == 'Doubles a number'
41 print double(155)