SoFunction
Updated on 2024-12-20

Thoroughly understand the callback function in Python (callback)

summaries

This is an introduction to the callback function in python.

What is a callback function

When a program is running, the application will normally call pre-prepared functions from the library via the API from time to time. However, some library functions require the application to pass a function to it first, so that it can call it at the right time to accomplish the target task.The function that is passed in and then called is called a callback function.

Example:

One hotel offers a wake-up call, but requires the traveler to decide the method of wake-up. They can call the guest room, send a bellhop to knock on the door, or, if they are dead asleep and afraid of being delayed, they can ask to have a pot of water poured over their heads. Here, "wake up" this behavior is provided by the hotel, equivalent to the library function, but the way to wake up by the traveler to decide and tell the hotel, that is, the callback function. The action of the traveler telling the hotel how to wake him up, that is, the action of passing the callback function into the library function, is called theRegistering a callback function(to register a callback function)

As you can see, callback functions are usually at the same abstraction level as the application (since what callback function is passed in is decided at the application level). And callbacks become a process where the higher level calls the lower level, and the lower level calls the higher level back. (This (I think) is where callbacks were first used, and why they got their name.

Advantages of the callback mechanism

The callback mechanism provides a very large amount of flexibility. Let's rename the library functions in the diagram asintermediate functionup, and that's because callbacks aren't just used between applications and libraries. Callbacks can be utilized anytime you want flexibility similar to the situation above. Some students may want toCallbacks seem to be just calls between functions, and a key difference can be found between the two

In callbacks, we utilize some way to pass callback functions into intermediate functions like parameters. It can be understood in this way that the intermediate function is incomplete until a callback function is passed in. In other words, the program can decide, change the behavior of the intermediate function at runtime by registering different callback functions. This is much more flexible than a simple function call.

#Callback function 1
# Generate an even number of the form 2k
def double(x):
    return x * 2
    
# Callback function 2
# Generate an even number of the form 4k
def quadruple(x):
    return x * 4
 
callback_demo.py`
 
from even import *
 
# Intermediate functions
# Accepts a function that generates an even number as an argument
# Returns an odd number
def getOddNumber(k, getEvenNumber):
    return 1 + getEvenNumber(k)
    
# Start function, here is the main function of the program
def main():    
    k = 1
    # When it is necessary to generate an odd number of the form 2k+1
    i = getOddNumber(k, double)
    print(i)
    # When an odd number of the form 4k+1 is required
    i = getOddNumber(k, quadruple)
    print(i)
    # When an odd number of the form 8k+1 is required
    i = getOddNumber(k, lambda x: x * 8)
    print(i)
    
if __name__ == "__main__":
    main()

Callback functions related to asynchronous processing

def apply_ascyn(func, args, callback):
    """
    The func function is the function that handles
    args are the arguments.
    callback is the action to be performed after the function has finished processing.
    """
    result = func(*args)
    callback(result)
 
def add(x, y):
    return x + y
 
def print_result(result):
    print(result)
 
apply_ascyn(add, (2, 3), callback=print_result)

Here print_result can only take a result argument, no other information can be passed in. Problems are encountered when trying to get the callback function to access the values of other variables or environment-specific variables.

Use a bind method instead of this simple function.

def appy_async(func, args, *, callback):
    result = func(*args)
    #Asynchronous execution of the function will also be executed after the return to this early jump out from this function
    callback(result)
 
def add(x ,y):
    return x + y
 
class ResultHandler(object):
    def __init__(self):
         = 0
 
    def handle(self, result):
         += 1
        print("[{}] Got: {}".format(, result))
 
resultHandler = ResultHandler()
appy_async(add, (2,3), callback=)

Use closures instead of the classes above to implement

def apply_async(func, args, *, callback):
    result = func(*args)
    callback(result)
 
def add(x ,y):
    return x + y
 
def make_handler():
    sequence = 0
    def handler(result):
        nonlocal sequence
        sequence += 1
        print("[{}] Got:{}".format(sequence, result))
    return handler
 
handler = make_handler()
apply_async(add, (2,3), callback=handler)

Asynchronous operations using concatenation

def apply_async(func, args, *, callback):
    result = func(*args)
    callback(result)
 
def add(x, y):
    return x + y
 
def make_handler():
    sequence = 0
    while True:
        result = yield
        sequence += 1
        print("[{}] Got:{}".format(sequence, result))
 
handle = make_handler()
next(handle)
 
apply_async(add, (2,3), callback=)

Blog post reference.

python3 callback function (callback) - know

summarize

to this article on the Python callback function (callback) of the article is introduced to this, more related Python callback function callback content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future!