Carrying Extra State with Callback Functions
Problem
You’re writing code that relies on the use of callback functions (e.g., event handlers, completion callbacks, etc.), but you want to have the callback function carry extra state for use inside the callback function.
Solution
This Shortcut pertains to the use of callback functions that are found in many libraries and frameworks—especially those related to asynchronous processing. To illustrate and for the purposes of testing, define the following function, which invokes a callback:
def
apply_async
(
func
,
args
,
*
,
callback
):
# Compute the result
result
=
func
(
*
args
)
# Invoke the callback with the result
callback
(
result
)
In reality, such code might do all sorts of advanced processing involving threads, processes, and timers, but that’s not the main focus here. Instead, we’re simply focused on the invocation of the callback. Here’s an example that shows how the preceding code gets used:
>>>
def
print_result
(
result
):
...
(
'Got:'
,
result
)
...
>>>
def
add
(
x
,
y
):
...
return
x
+
y
...
>>>
apply_async
(
add
,
(
2
,
3
),
callback
=
print_result
)
Got: 5
>>>
apply_async
(
add
,
(
'hello'
,
'world'
),
callback
=
print_result
)
Got: helloworld
>>>
As you will notice, the print_result()
function only accepts a single argument, which is the result. No other information is passed ...
Get Carrying Extra State with Callback Functions now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.