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?
Here's what you wanted to do :
Your code is executed as follows:
callback
function is called with(1, 2)
and it returnsNone
(Without return statement, your function printsSum = 3
and returnsNone
)main
function is called withNone
as argument (Socallback != None
will always beFalse
)As mentioned in the comments, your callback is called whenever it's suffixed with open and close parens; thus it's called when you pass it.
You might want to use a lambda and pass in the values.
In this code
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 printingSum = 3
.Since
callback
returns no explicit value, it is returned asNone
.Thus, your code is equivalent to
Solution
You could try not calling the function at first and just passing its handle.
The problem is that you're evaluating the callback before you pass it as a callable. One flexible way to solve the problem would be this:
Optionally you may want to include a way to support keyword arguments.