python - Decorator

Subscribe Send me a message home page


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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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 -----

Send me a message Subscribe to blog updates

Want some fun stuff?

/static/shopping_demo.png


Comments