Home Coding & Scripting Callbacks in Python

Callbacks in Python

329
0

When you learned about functions in Python in the blog post Functions in Python, you saw that functions are reusable blocks of code. They make your programs cleaner, shorter, and easier to manage.

But Python goes one step further: not only can you call a function, you can also pass a function into another function. This idea is called a callback.


📝 If You Want to Practice the Code

If you plan to practice the Python code mentioned within this blog post, you’ll need a working Python environment. You can execute the commands in one of the following ways (choose only one option):

👉 Choose whichever environment you’re most comfortable with. If you haven’t set up Python yet, start with one of the installation posts before trying the examples here.


🔹 What is a Callback?

A callback is just a function you give as an input to another function, so the other function can call it when needed.

Think of it like giving someone your phone number and asking them to call you when dinner is ready. You don’t know when dinner will be done, but you trust them to “call you back.”


🔹 A Simple Example

def greet(name):
    print("Hello,", name)

def process_user(callback):
    # Imagine this function does some work
    user_name = "Alice"
    # Then it calls the function you passed in
    callback(user_name)

process_user(greet)

👉 Output:

Hello, Alice

Here, greet is the callback function. We passed it into process_user, and process_user called it back later.


🔹 Callbacks with Parameters

You can also use anonymous functions (lambdas) as callbacks:

def process_number(num, callback):
    result = num * 2
    callback(result)

process_number(5, lambda x: print("Result is", x))

👉 Output:

Result is 10

This way, you don’t need to define a separate function if the logic is simple.


🔹 Why Use Callbacks?

Callbacks are useful when:

  • You want your code to be flexible.
  • You don’t know ahead of time what exact action should be taken.
  • You’re working with events (like button clicks, timers, or async tasks).

🔹 A Real-Life Analogy

  • Without callback: You wait in the kitchen until dinner is ready.
  • With callback: You go read a book, and when dinner is ready, someone calls you.

Callbacks help programs avoid “waiting around” and instead respond when something happens.


🔹 A Cloud Example (Practice Later): Azure Authentication with Callback

📝 Note: Please just read through this Azure example for seeing how callbacks are used. Don’t try to practice it yet — we have a different hands-on post for this later once we’ve set up Azure Cloud. Also, don’t worry if you don’t understand it all right now — we’ll have a separate explanation blog post for this after the hands-on post.

Callbacks are very useful in cloud programming. For example, when authenticating with Azure using the DeviceCodeCredential, you can pass a callback function to display the login instructions for the user:

from azure.identity import DeviceCodeCredential
from azure.mgmt.resource import ResourceManagementClient

# Replace with your subscription ID and tenant ID
subscription_id = "YOUR_SUBSCRIPTION_ID"
tenant_id = "YOUR_TENANT_ID"

def show_message(verification_uri, user_code, expires_on):
    print(f"To authenticate, visit: {verification_uri}")
    print(f"Enter the code: {user_code}")
    print(f"(Code expires on: {expires_on})")

# Authenticate with tenant-specific credentials
credential = DeviceCodeCredential(
    tenant_id=tenant_id,
    prompt_callback=show_message
)

# Example: create a client
client = ResourceManagementClient(credential, subscription_id)

# Creating a resource group (this first SDK call will trigger login)
for rg in client.resource_groups.list():
    print(rg.name)

👉 Here, the show_message function is a callback passed into DeviceCodeCredential.

It will actually be called the very first time Azure needs to authenticate you — for example, when you try to make the first request using the client (client.resource_groups.list() in this case).

At that moment:

  1. Azure generates a device login URL and code.
  2. The SDK “calls back” your show_message function with these details.
  3. You (the user) open the link, enter the code, and complete the authentication.
  4. After successful login, Azure continues running the program normally without calling the callback again unless re-authentication is needed.

This way, the program doesn’t need to hardcode how login instructions are shown — instead, it uses your callback function to handle it flexibly.

✨ Without the callback mechanism, you would have had to manually poll or hardcode how login instructions are displayed, which means writing extra logic to capture and print the verification code and URL yourself. The callback removes that extra work by letting Azure call your function automatically at the right time.

📖 To understand this program fully, you can also refer to the blog post Explaining the Python Program That Connects to Azure From Google Colab.


📝 Mini Task

Try writing these yourself:

  1. A function do_math(a, b, callback) that uses the callback to add, subtract, or multiply.
    Example: do_math(3, 4, lambda x, y: x + y) → 7.
  2. A function apply_callback(values, callback) that applies the callback to every item in a list.
    Example: apply_callback([1,2,3], lambda x: x * x) → 1, 4, 9.

✅ Summary

  • A callback is a function you pass into another function.
  • The function gets “called back” later.
  • Callbacks make programs more flexible and are common in event-driven and async programming.

By building on your knowledge from the Functions in Python post, callbacks give you the power to write Python programs that respond dynamically and handle events smoothly.

Previous articleFunctions in Python
Next articleClasses and Objects in Python
Heartin Kanikathottu
As a seasoned Cloud and Security Architect, I’ve led transformative initiatives in key roles, including Vice President at Morgan Stanley, Principal Architect at Societe Generale, and Tech Lead & Cloud Security Architect at VMware, among others. I’m also an internationally published author with multiple books available on platforms like Amazon and O'Reilly. Notably, one of my books was recognized as the 8th best cloud computing book of all time in 2020, reflecting the impact of my contributions to the field. With over 15 professional certifications from providers such as Microsoft (Azure), Amazon (AWS), Oracle (Java), Pivotal (Spring), and IBM, I bring a wealth of expertise to my work. Academically, I hold dual Master’s degrees in Cloud Computing and Data Analytics. I’m passionate about sharing knowledge and mentoring others, which is why I actively speak at global technical forums such as Tech Opportunities Fest at Platform Calgary, Google's Kubernetes Meetup, Java User Group, Elasticsearch Meetup, and the Agile India Conference.

LEAVE A REPLY

Please enter your comment!
Please enter your name here