Callback Function

(Wikipedia) In computer programming, a callback is any executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at a given time.

This execution may be immediate or it might happen at a later time. In all cases, the intention is to specify a function or subroutine as an entity that is (depending on the language), more or less similar to a variable.

To be simple, a "callback" is any function that is called by another function which takes the "callback" function as a parameter.

Now we are going to see how to implement a very trivial callback mechanism in Python.

def say_name():
    print("Sniffy")

def say_hello(p1, callback):
    print(p1)
    callback()

# call say_hello with say_name as an argument
say_hello("Hello", say_name)

In the code shown above, the first function say_name() is an ordinary function.

The second function has two parameters: the first parameter p1 is an ordinary parameter that accept a string value; the second parameter callback is a name of a function.

We pass the function say_name as an argument when we invoke say_hallo("Hello", say_name). say_name() acts as a callback function.

As output, we’ll have:

Hello
Sniffy

results matching ""

    No results matching ""