Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a simple callback function?

Python 2.7.10

I wrote the following code to test a simple callback function.

def callback(a, b):
    print('Sum = {0}'.format(a+b))

def main(callback=None):
    print('Add any two digits.')
    if callback != None:
        callback

main(callback(1, 2))

I receive this when I execute it:

Sum = 3
Add any two digits.

Why Add any two digits is after Sum = 3? I guess it is because the callback function executes first. How to execute the callback function after all other code in main() executed?

like image 246
srgbnd Avatar asked Nov 28 '16 11:11

srgbnd


People also ask

How do you write a function back call?

A custom callback function can be created by using the callback keyword as the last parameter. It can then be invoked by calling the callback() function at the end of the function. The typeof operator is optionally used to check if the argument passed is actually a function. console.

What are callback functions with an example?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. The above example is a synchronous callback, as it is executed immediately.

What is callback function in JavaScript simple example?

Example: Using a Callback FunctionThe sayName() function is passed as an argument to the greet() function. The setTimeout() method executes the greet() function only after 2 seconds. However, the sayName() function waits for the execution of the greet() function.

What is callback () in JavaScript?

A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.


2 Answers

In this code

if callback != None:
    callback

callback on its own doesn't do anything; it accepts parameters - def callback(a, b):

The fact that you did callback(1, 2) first will call that function, thereby printing Sum = 3, and then main() gets called with the result of the callback function, which is printing the second line

Since callback returns no explicit value, it is returned as None.

Thus, your code is equivalent to

callback(1, 2)
main()

Solution

You could try not calling the function at first and just passing its handle.

def callback(n):
    print("Sum = {}".format(n))

def main(a, b, _callback = None):
    print("adding {} + {}".format(a, b))
    if _callback:
        _callback(a+b)

main(1, 2, callback)
like image 54
OneCricketeer Avatar answered Oct 05 '22 22:10

OneCricketeer


Here's what you wanted to do :

def callback(a, b):
    print('Sum = {0}'.format(a+b))

def main(a,b,f=None):
    print('Add any two digits.')
    if f is not None:
        f(a,b)

main(1, 2, callback)
like image 44
Eric Duminil Avatar answered Oct 05 '22 22:10

Eric Duminil