Source: avechenri on Unsplash
Instead of assigning the *result* of a function call to a variable, you can assign the function *itself*.
def greet(name):
return f"Hello, {name}!"
# Assign the function 'greet' to the variable 'say_hello'
say_hello = greet
# Now you can call the function through the variable
message = say_hello("World")
print(message) # Output: Hello, World!
You can pass a function as an argument to another function. This is a key concept in higher-order functions.
def square(x):
return x * x
def cube(x):
return x * x * x
def my_map(func, iterable):
"""Applies a function to each item of an iterable."""
result = []
for item in iterable:
result.append(func(item))
return result
numbers = [1, 2, 3, 4, 5]
# Pass the 'square' function to 'my_map'
squared_numbers = my_map(square, numbers)
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
# Pass the 'cube' function to 'my_map'
cubed_numbers = my_map(cube, numbers)
print(cubed_numbers) # Output: [1, 8, 27, 64, 125]
A function can return another function. This is fundamental to closures and decorators.
def logger(prefix):
"""Returns a function that logs messages with a prefix."""
def log_message(message):
print(f"[{prefix}] {message}")
return log_message
# 'log_info' is now a function
log_info = logger("INFO")
log_info("Application started") # Output: [INFO] Application started
log_info("User logged in") # Output: [INFO] User logged in
log_error = logger("ERROR")
log_error("File not found") # Output: [ERROR] File not found
Understanding first-class functions is crucial for grasping more advanced Python concepts: