Python Decorators
What are Python decorators?
Python decorators are special syntax of the language that allows for functions to be applied to other functions or classes. The Python Enhancement Proposal (PEP) 318 describes the syntax used by these decorators as applied to functions. The Python Enhancement Proposal (PEP) 3129 describes the syntax used by these decorators as applied to classes.
The first use of decorator notation of @function_name appeared in Python 2.2. The decorators for class methods and static functions were created so instead of using the following for a classmethod or a staticmethod:
class Foo(object):
def bar(cls):
pass
bar = classmethod(bar)
class Biz(object):
def baz():
pass
baz = staticmethod(baz)
The new decorator syntax allows you to call the __builtins__ functions, classmethod() and staticmethod() by using an @function_name syntax. This applied either the classmethod or staticmethod built-in functions to the function that followed the @function_name syntax.
class Foo(object):
@classmethod
def bar(cls):
pass
class Biz(object):
@staticmethod
def baz():
pass
Properties
Properties are a special case of the use of decorators. In the case of properties, the property function gets called on the function that is either a attribute setter, getter, deleter method of a class. The following two examples are equivalent (taken from https://wiki.python.org/moin/PythonDecoratorLibrary)
class C(object):
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
Examples of decorators
There is a repository containing numerous examples at https://wiki.python.org/moin/PythonDecoratorLibrary.