8 Decorator

8.1 Definition

  • Decorator is a function that accept callable as the only argument
  • The main purpose of decarator is to enhance the program of the decorated function
  • It returns a callable

8.2 Examples

8.2.1 Example 1 - Plain decorator function

  • Many times, it is useful to register a function elsewhere - for example, registering a task in a task runner, or a functin with signal handler
  • register is a decarator, it accept decorated as the only argument
  • foo() and bar() are the decorated function of register
registry = []

def register(decorated):
    return decorated

def foo():
    return 3

def bar():
    return 5
#:> [<function foo at 0x7f3de18b3710>, <function bar at 0x7f3de18b3ef0>]
#:> 3
#:> 5

8.2.2 Example 2 - Decorator with Class

  • Extending the use case above
  • register is the decarator, it has only one argument
class Registry(object):
    def __init__(self):
        self._functions = []
    def register(self,decorated):
        return decorated
    def run_all(self,*args,**kwargs):
        return_values = []
        for func in self._functions:
        return return_values

The decorator will decorate two functions, for both object a and b

a = Registry()
b = Registry()

def foo(x=3):
    return x

def bar(x=5):
    return x

def bax(x=7):
    return x

Observe the result

print (a._functions)
#:> [<function foo at 0x7f3de1891200>, <function bax at 0x7f3de9689e60>]
print (b._functions)
#:> [<function bar at 0x7f3de18914d0>, <function bax at 0x7f3de9689e60>]
print (a.run_all())
#:> [3, 7]
print (b.run_all())
#:> [5, 7]
print ( a.run_all(x=9) )
#:> [9, 9]
print ( b.run_all(x=9) )
#:> [9, 9]