callback
In Python, a callback is a function that you pass as an argument to another function. The receiving function can then call the callback at a later point, often as a response to an event or after completing a task.
Callbacks are a powerful way to customize the behavior of functions and are commonly used in asynchronous programming, event handling, and GUI applications.
Example
Here’s an example of a callback function in Python:
>>> def greet(name):
... print(f"Hello, {name}!")
...
>>> def process_user_input(callback):
... name = input("Enter your name: ")
... callback(name)
...
>>> process_user_input(greet)
Enter your name: Pythonista
Hello, Pythonista!
In this example, greet()
is a callback function that gets called by process_user_input()
. When the user enters their name, process_user_input()
calls greet()
, which then prints a greeting message.
Related Resources
Tutorial
Defining Your Own Python Function
Learn how to define your own Python function, pass data into it, and return results to write clean, reusable code in your programs.
For additional information on related topics, take a look at the following resources:
- Python Closures: Common Use Cases and Examples (Tutorial)
- Functional Programming in Python: When and How to Use It (Tutorial)
- Defining and Calling Python Functions (Course)
- Defining Your Own Python Function (Quiz)
- Defining Your Own Python Function (Quiz)
- Python Closures: Common Use Cases and Examples (Quiz)
- Functional Programming in Python: When and How to Use It (Quiz)
By Leodanis Pozo Ramos • Updated April 10, 2025