How to understand python decorator correctly

  • 2021-11-10 10:14:14
  • OfStack

Catalog 1. Closures 2. Decorators 3. Decorators with parameters 4. Class decorators

1. Closures

To understand decorators, you must first understand a concept, closure. What is a closure? In other words, nesting another function in a function and referring to the variables of an external function is a closure. Just saying that there is no concept, give an example directly.


def outer(x):
    def inner(y):
        return x + y
    return inner

print(outer(6)(5))
-----------------------------
>>>11

As the code shows, within the outer function, another inner function is defined, and the inner function references the variable x of the external function outer, which is a closure. In the output, outer (6) (5), the value passed in the first parenthesis returns inner function, which actually returns 6 + y, so if you pass in the second parameter, you can get the return value, 6 + 5.

STEP 2 Decorators

Next, we will talk about decorators. In fact, decorators are a closure, and decorators are an application of closures. What is a decorator? In short, python decorator is a function used to expand the original function. The special feature of this function is that its return value is also a function. The advantage of using python decorator is to add new functions to the function without changing the original function code. When using, add @ demo before the required function.


def debug(func):
    def wrapper():
        print("[DEBUG]: enter {}()".format(func.__name__))
        return func()
    return wrapper

@debug
def hello():
    print("hello")

hello()
-----------------------------
>>>[DEBUG]: enter hello()
>>>hello

The decorator in the example adds a function into the debug mode of the function, and completes this function without modifying the original function code, which can be said to be very convenient.

3. Decorator with parameters

The above example of the decorator is not the function is too simple, then decorator can add 1 some parameters, of course, it is possible, in addition, the decorative function is of course also can pass parameters.


def logging(level):
    def outwrapper(func):
        def wrapper(*args, **kwargs):
            print("[{0}]: enter {1}()".format(level, func.__name__))
            return func(*args, **kwargs)
        return wrapper
    return outwrapper

@logging(level="INFO")
def hello(a, b, c):
    print(a, b, c)

hello("hello,","good","morning")
-----------------------------
>>>[INFO]: enter hello()
>>>hello, good morning

As above, parameters can be passed in the decorator, forming a complete decorator first, and then decorating the function. Of course, if the function needs to pass in parameters, it can be received with variable-length parameter symbols. In the example, three parameters are passed in.

4. Class decorators

Decorator can only be written by function, and can also use class decorator. The usage is not much different from function decorator. In essence, __call__ magic method in class method is used to realize direct call of class.


class logging(object):
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        print("[DEBUG]: enter {}()".format(self.func.__name__))
        return self.func(*args, **kwargs)

@logging
def hello(a, b, c):
    print(a, b, c)

hello("hello,","good","morning")
-----------------------------
>>>[DEBUG]: enter hello()
>>>hello, good morning

Class decorators can also take parameters, as follows


class logging(object):
    def __init__(self, level):
        self.level = level

    def __call__(self, func):
        def wrapper(*args, **kwargs):
            print("[{0}]: enter {1}()".format(self.level, func.__name__))
            return func(*args, **kwargs)
        return wrapper
        
@logging(level="TEST")
def hello(a, b, c):
    print(a, b, c)

hello("hello,","good","morning")
-----------------------------
>>>[TEST]: enter hello()
>>>hello, good morning

Well, the above is the decorator 1 some concepts and general usage, want to more in-depth understanding of decorator or need to be more experience in the usual practice and application

The above is how to correctly understand the details of python decorator, more information about python decorator please pay attention to other related articles on this site!


Related articles: