Higher-Order Functions in Python.
Function
It can take one or more functions as parameters.It can be returned as a result of another function.It can be modified.It can be assigned to a variable.
Function as a Return Value
def square(x): # a square function return x ** 2 def cube(x): # a cube function return x ** 3
Python Decorators
A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators call before the definition of a function you want to decorate.
Creating Decorators
To create a decorator function, we need an outer function with an inner wrapper function.
def welcome(): return 'Hey Hello' def makeMeLower(function): def cont(): func = function() make_lowercase = func.lower() return make_lowercase return cont output = makeMeLower(welcome) print(output()) # hey hello
Accepting Parameters in Decorator Functions
We need our functions to take parameters most of the time, so we might need to define a decorator that accepts parameters.
def withParams(function): def acceptParams(p1, p2): function(p1, p2) print("I live in {}".format(p2)) return acceptParams @withParams def printMe(name, country): print("I am {} and I Know Coding.".format( name, country)) printMe("Adam",'Birmingham') # I am Adam, and I Know Coding. # I live in Birmingham
Built-in Higher-Order Functions
- Some of the built-in higher-order functions covered in this part are
map()
,filter
, andreduce
. - Lambda function can be passed as a parameter, and the best use case of lambda functions is in functions like
map
,filter
, andreduce
.
Python - Map Function
The
map()
function is a built-in function that takes a function and is iterable as parameters.
# syntax map(function, iterable)
nums = ['1', '2', '3', '4', '5'] output = map(int, nums) print(list(output)) # [1, 2, 3, 4, 5]
names = ['Adam', 'Lovlin', 'Anderson', 'Pope'] def upperMe(name): return name.upper() output = map(upperMe, names) print(list(output)) # ['ADAM', 'LOVLIN', 'ANDERSON', 'POPE']
Python - Filter Function
- The
filter()
function calls the specified function, which returns a boolean for each item of the specified iterable (list). - It filters the items that satisfy the filtering criteria.
# syntax filter(function, iterable)
numbers = [1, 2, 3, 4, 5] # iterable def findOdd(num): if num % 2 != 0: return True return False output = filter(findOdd, numbers) print(list(output)) # [1, 3, 5]
Python - Reduce Function
- The
reduce()
function is defined in the functools module, and we should import it from this module. - Like
map
andfilter
, it takes two parameters, a function and an iterable. - However, it doesn't return another iterable. Instead it returns a single value.
from functools import reduce nums = ['1', '2', '3', '4', '5'] # iterable def add(x, y): return int(x) + int(y) total = reduce(add, nums) print(total) # 15