Callback in Python

 

What are Callbacks in Python?

A callback is a function that is passed as an argument to another function and is called later inside that function to complete a specific task.

In simple terms:

A callback is a function you give to another function so that it can call it when needed.


✅ Why Use Callbacks?

  • To customize the behavior of a function

  • To handle events (e.g., in GUIs or web frameworks)

  • To process results (e.g., in asynchronous programming)

  • To simplify code reuse and abstraction


✅ Basic Example of a Callback Function

def greet(name):
print(f"Hello, {name}!") def process_user(callback): user_name = "Alice" callback(user_name) process_user(greet)

Output:

Hello, Alice!

📝 Here:

  • greet is a callback function.

  • process_user accepts the callback and calls it with data.


✅ Example: Using Callbacks to Customize Behavior

def square(x):
return x * x def cube(x): return x * x * x def apply_function(func, value): result = func(value) print(f"Result: {result}") apply_function(square, 3) # Output: Result: 9 apply_function(cube, 3) # Output: Result: 27

📝 square and cube are callback functions passed to apply_function.


✅ Real-World Example: Sorting with a Callback (Key Function)


names = ["Charlie", "Alice", "Bob"] # Sort based on the length of the name sorted_names = sorted(names, key=lambda name: len(name)) print(sorted_names) # Output: ['Bob', 'Alice', 'Charlie']

📝 The lambda here acts as a callback passed to sorted().


✅ Summary

TermMeaning
Callback                                A function passed as an argument
Used in                                Sorting, GUI events, web apps, async programming
Benefit                                Flexible, reusable, customizable behavior

Comments

Popular posts from this blog

Python For Application Development MNCST 309 KTU BTech CS Minor 2024 Scheme - Dr Binu V P

Course Details MNCST 309 Python For Application Development

Regular Expression