Python Callback Function
Python Callback Function
Before implementing Callback Function in Python, first we will brush our understanding about what a Callback Function is.
A callback is a function that is passed as an argument to other function. This other function is expected to call this callback function in its definition. The point at which other function calls our callback function depends on the requirement and nature of other function.
Callback Functions are generally used with asynchronous functions.
Example for Callback Function: Callback Function can be passed to a function to print out the size of file after the function reads given text file.
Examples
1. A simple example for a Callback function
In this example, we will define a function named printFileLength()
that takes file path and callback functions as arguments.
printFileLength()
reads the file, gets the length of the file and at the end makes a call to the callback function.
Python Program
def callbackFunc(s):
print('Length of the text file is : ', s)
def printFileLength(path, callback):
f = open(path, "r")
length = len(f.read())
f.close()
callback(length)
if __name__ == '__main__':
printFileLength("sample.txt", callbackFunc)
Output
Length of the text file is : 56
You may pass different callback function as required. In the following program, we will define two functions callbackFunc1() and callbackFunc2() which we will use as callback functions for printFileLength(). But, we do not change the definition of printFileLength() function.
Python Program
def callbackFunc1(s):
print('Callback Function 1: Length of the text file is : ', s)
def callbackFunc2(s):
print('Callback Function 2: Length of the text file is : ', s)
def printFileLength(path, callback):
f = open(path, "r")
length = len(f.read())
f.close()
callback(length)
if __name__ == '__main__':
printFileLength("sample.txt", callbackFunc1)
printFileLength("sample.txt", callbackFunc2)
Output
Callback Function 1: Length of the text file is : 56
Callback Function 2: Length of the text file is : 56
Summary
In this tutorial of Python Examples, we learned what a Callback Function is, and how to implement a Callback Function in Python, with examples.