python callback functions code example

Example 1: callback function

function greeting(name) {
  alert('Hello ' + name);
}

function processUserInput(callback) {
  var name = prompt('Please enter your name.');
  callback(name);
}

processUserInput(greeting);

Example 2: callback function

function createQuote(quote, callback){ 
  var myQuote = "Like I always say, " + quote;
  callback(myQuote); // 2
}

function logQuote(quote){
  console.log(quote);
}

createQuote("eat your vegetables!", logQuote); // 1

// Result in console: 
// Like I always say, eat your vegetables!

Example 3: python callback

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.

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(sum):
    print("Sum = {}".format(sum))

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

main(1, 2, callback)