Advanced Python Functions and Lambdas
Posted on June 1, 2024 (Last modified on June 8, 2024) • 2 min read • 314 wordsDive deeper into Python with advanced functions and lambdas, exploring closures, decorators, and higher-order functions.
Enhance your Python skills with advanced functions, including closures, decorators, and lambdas. These concepts will help you write cleaner and more efficient code.
A closure is a function object that remembers values in enclosing scopes even if they are not present in memory.
def outer_function(msg):
def inner_function():
print(msg)
return inner_function
hello_func = outer_function("Hello")
hello_func() # Output: Hello
Closures are useful for creating functions with data that persists between calls.
def make_multiplier(x):
def multiplier(n):
return x * n
return multiplier
multiply_by_3 = make_multiplier(3)
print(multiply_by_3(10)) # Output: 30
Decorators are a way to modify or enhance functions without changing their definition.
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print("Wrapper executed before {}".format(original_function.__name__))
return original_function(*args, **kwargs)
return wrapper_function
@decorator_function
def display():
print("Display function ran")
display()
Decorators can also accept arguments.
def decorator_with_args(decorator_arg1, decorator_arg2):
def decorator(original_function):
def wrapper_function(*args, **kwargs):
print(f"Decorator args: {decorator_arg1}, {decorator_arg2}")
return original_function(*args, **kwargs)
return wrapper_function
return decorator
@decorator_with_args("Hello", "World")
def greet(name):
print(f"Hi, {name}!")
greet("Alice")
Lambdas are small anonymous functions defined using the lambda
keyword.
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8
Lambdas are often used with functions like map()
, filter()
, and sorted()
.
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]
Functions that take other functions as arguments or return them as results.
def apply_func(func, value):
return func(value)
result = apply_func(lambda x: x * 2, 5)
print(result) # Output: 10
Higher-order functions allow you to create more flexible and reusable code.
def apply_operation(operation, numbers):
return [operation(n) for n in numbers]
double = lambda x: x * 2
nums = [1, 2, 3, 4]
print(apply_operation(double, nums)) # Output: [2, 4, 6, 8]
Understanding these advanced function concepts will significantly enhance your Python programming skills. Practice using closures, decorators, and lambdas to write more modular and reusable code.