Python Mastery – From Basics to Brilliance / Functions

Callbacks

πŸ“ž Callback Functions

A callback function is a function that is passed to another function as an argument and is called later by that function.

Callbacks are commonly used with higher-order functions.


πŸ”Ή Basic Example

def greet():
    print("Hello!")

def execute(callback):
    callback()

execute(greet) #Hello!

Here:

greet        β†’ Callback function πŸ“ž
execute()    β†’ Receives and calls the callback

πŸ”Ή Callback with Arguments

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

def execute(callback):
    callback("Codeveda")

execute(greet) #Hello Codeveda

The execute() function decides when and how to call greet().


⚑ Callback with Lambda

A lambda can also be used as a callback:

def execute(callback):
    print(callback(10))

execute(lambda x: x * 2) #20

Here, the lambda function is passed as the callback.


πŸ”— Callback vs Higher-Order Function

These concepts are closely related:

Higher-Order Function
        ↓
Accepts a function
        ↓
That function can act as a Callback

Example:

def double(x):
    return x * 2

def process(callback, value):
    return callback(value)

print(process(double, 5)) #10

Here:

  • double β†’ Callback function πŸ“ž

  • process β†’ Higher-order function πŸ”