close

How to write a simple callback function?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to write a simple callback function in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to write a simple callback function?

  1. How to write a simple callback function?

    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

  2. write a simple callback function

    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

Method 1

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)

Method 2

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)

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read