Python function decorators can replace the decorated function with another function.

1 basis

def deco(func):
    def inner():
        logging.info('inner -> %s','running')
    return inner


@deco
def target():
    logging.info('target -> %s', 'running')


target()
logging.info('target -> %s',target)
Copy the code

Running results:

  1. This example first defines a function called deco that defines an inner function and then returns the inner function.
  2. Next, using the function decorator syntax, we decorate the function named target;
  3. Finally, the target function is called.

You can see that the inner() function is actually called, and that the target function is replaced by the inner function.

2 Operating Mode

The decorator is executed in the code that defines the decorator function.

registry = []


def register(func):
    logging.info('[register] func -> %s', func)
    registry.append(func)
    return func


@register
def f1():
    logging.info('f1 -> %s', f1)


@register
def f2():
    logging.info('f2 -> %s', f2)


def f3():
    logging.info('f3 -> %s', f3)


def main():
    logging.info('main -> %s', main)
    logging.info('registry -> %s', registry)
    f1()
    f2()
    f3()


if __name__ == '__main__':
    main()
Copy the code

Running results:

  1. We first define a decorator function called register, which decorates the f1() and f2() functions. The f3() function here, for comparison, is not decorated;
  2. The result shows the order of execution: the decorator function is executed before the main function;
  3. join__name__ == '__main__'This is so that the Python file can be imported as a module into other files1. Since Python files are executed from the top down by default, the main() code is not executed after import. After all, the purpose of an import is to use the functions or class methods it defines.

Practical application process:

  1. It is usually defined in a separate module and imported into other modules when used.
  2. The function decorator defines a new function internally and returns it.

  1. The function of the ‘main’ module in Python.
  2. Luciano Ramalho, An Dao, Wu Ke. Smooth Python[M]. Posts and Telecommunications Press, 2017:301-305.