Python Decorator
When refactoring a codes, we need to extract duplicated features from different methods or functions. A magic in Python 3 is to decorate the a striped basic functions with sharing features.
What is decorator?
A (almost) minimal demo:
from functools import wraps
def my_decorator(func):
# to make sure func name are included.
@wraps(func)
def wrapper(x):
""" function wrapper of my_decorator """
print(" Hi, ") + func.__name__ + " return.")
return func(x)
return wrapper
# use decorator
@my_decorator
def foo(x):
return x + 1
foo(10)
Why decorator?
- Memoization: speed up function evaluation by storing the
{input: output}
dict. - Decorate a function with additional processes which probably are duplicated from other funcs. For example, you can count the evaluation times in a decorator.
Use class as a decorator
You can transform class into function by adding a __call__
method to the class.
Decorator demo:
class my_decorator:
def __init__(self, f):
self.f = f
def __call__(self):
print("Decorating ", self.f.__name__)
self.f()
@my_decorator
def foo():
print("hello from foo")
Further reading: Python3 decorators tutorial