In this tutorial, we will learn how to pass a callback function in Python. A callback function is a function that is passed as an argument to another function and is called at some point during the execution of that function. This allows you to create more flexible, modular, and maintainable code.
Step 1: Define the Callback Function
First, we need to define the callback function that we want to pass to another function. Let’s create a simple callback function that prints a message:
1 2 |
def my_callback(): print("Hello from the callback function!") |
Step 2: Create a Function That Accepts a Callback Function as an Argument
Now, we’ll create another function that will accept our callback function as an argument:
1 2 3 |
def function_with_callback(callback): print("I'm in the function_with_callback() function.") callback() |
In the code above, we have defined a function named function_with_callback()
which takes one parameter called callback
. The callback
parameter will be used to store the reference to the callback function we want to pass.
Step 3: Call the Function and Pass the Callback
Finally, let’s call our function_with_callback()
function and pass our my_callback()
function as an argument:
1 |
function_with_callback(my_callback) |
The output of this code would be:
I'm in the function_with_callback() function. Hello from the callback function!
Step 4: Using Callback Functions with Arguments
In some cases, you may want the callback function to accept one or more arguments. Here’s how you can pass arguments to the callback function:
1 2 3 4 5 6 7 8 |
def my_callback_with_args(message): print("Callback: " + message) def function_with_callback(callback, message): print("I'm in the function_with_callback() function.") callback(message) function_with_callback(my_callback_with_args, "Hello from the callback function with arguments!") |
The output of this code would be:
I'm in the function_with_callback() function. Callback: Hello from the callback function with arguments!
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
def my_callback(): print("Hello from the callback function!") def function_with_callback(callback): print("I'm in the function_with_callback() function.") callback() function_with_callback(my_callback) def my_callback_with_args(message): print("Callback: " + message) def function_with_callback(callback, message): print("I'm in the function_with_callback() function.") callback(message) function_with_callback(my_callback_with_args, "Hello from the callback function with arguments!") |
Conclusion
In this tutorial, we learned how to pass a callback function in Python, both with and without arguments. By using callback functions, you can create more flexible, modular, and maintainable code.