SoFunction
Updated on 2024-10-29

Two insights into the use of Python decorators

Basic use of decorators (decorating functions with parameters)

def decorator(func):
    def inner(info):
        print('inner')
        func(info)
    return inner

@decorator
def show_info(info):
    print(info)

show_info('hello')

Prevent the decorator from changing the name of the decorated function

Decorator in the decoration of the function as a result of the return of the function address of the inner, so the name of the function will also change show_info.__name__ will become the inner, to prevent this phenomenon you can use functools

import functools

def decorator(func):
	@(func)
    def inner(info):
        print('inner')
        func(info)
    return inner

@decorator
def show_info(info):
    print(info)

show_info('hello')

Writing it this way does not change the name of the decorated function

Decorator Dynamic Registration Functions

This method is represented in the source code of the Flask framework's ()

class Commands(object):
    def __init__(self):
         = {}

    def regist_cmd(self, name: str) -> None:
        def decorator(func):
            [name] = func
            print('func:',func)
            return func
        return decorator

commands = Commands()

# Make the value of s1 point to the function address of show_h
@commands.regist_cmd('s1')
def show_h():
    print('show_h')

# Make the value of s2 point to the address of show_e's function
@commands.regist_cmd('s2')
def show_e():
    print('show_e')

func = ['s1']
func()

Personal experience

You can use plus (func_name) when reading the decorator code
consider as an example

@commands.regist_cmd('s2')
def show_e():
    print('show_e')

i.e. show_e = commands.regist_cmd('s2')(show_e)

This article on the use of Python decorator of the two articles are introduced to this, more related to the use of Python decorator content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!