.. getthecode:: decorators.py :language: python3 :hidden: ============ Decorators ============ This page contains a memo on decorators. .. code-block:: py3 from Tools import * Function Decorators ------------------- `PEP 318 -- Decorators for Functions and Methods `_ .. code-block:: py3 def func_decorator_1(func): print_function('func_decorator_1', func) # do something with func # func.attribute = ... return func def func_decorator_2(func): print_function('func_decorator_2', func) return func # Same as foo = func_decorator_2(func_decorator_1(foo)) @func_decorator_2 @func_decorator_1 def foo(): pass .. code-block:: none @func_decorator_1 @func_decorator_2 .. code-block:: py3 class func_decorator_3: def __init__(self, *args, **kwargs): print_method(self, '__init__', args, kwargs) def __call__(self, func): print_method(self, '__call__', func) return func # Same as foo = func_decorator_3(*args, **kwargs)(foo) @func_decorator_3(1, 2, attr1='abc') def foo(): pass .. code-block:: none @func_decorator_3.__init__ (1, 2) {'attr1': 'abc'} @func_decorator_3.__call__ Class Decorators ---------------- `PEP 3129 -- Class Decorators `_ .. code-block:: py3 def class_decorator_1(cls): print_function('class_decorator_1', cls) # cls.attribute = ... return cls def class_decorator_2(cls): print_function('class_decorator_2', cls) return cls # Same as A = class_decorator_2(class_decorator_1(A)) @class_decorator_2 @class_decorator_1 class A: pass .. code-block:: none @class_decorator_1 @class_decorator_2