There is nothing special about python decorator. It's just a function that takes another function as an input and returns a new function with additional features. In the example below, printHello
is a decorator and it's applied to the calculateSum
function.
1234567891011121314
def printHello(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
print("Hello")
return fn(*args, **kwargs)
return wrapper
@printHello
def calculateSum(a, b):
return a + b
print(calculateSum.__name__)
v = calculateSum(1, 2)
print(v)
The output of the above program is
calculateSum Hello 3
As we can see, a hello message is printed before the result.
We can use a decorator for instance methods as well. For example:
1234567891011121314151617181920
def refreshCacheFirst(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
assert len(args) > 0 and isinstance(args[0], MyClass)
obj = args[0]
obj.refreshCache()
return fn(*args, **kwargs)
return wrapper
class MyClass:
def refreshCache(self):
print("refresh cache")
@refreshCacheFirst
def doSomething(self):
print("do something")
instance = MyClass()
instance.doSomething()
The output is as follows:
refresh cache do something
This works because the first argument of an instance method in python is the instance itself.
----- END -----
©2019 - 2022 all rights reserved