DEV Community

loading...
Cover image for Higher-order function in python

Higher-order function in python

Jajuan Hall
A blog for aspiring developers
・2 min read

Introduction

A Higher-order function is a function that takes another function as a parameter or a function that returns a function. The built-in map, filter, and reduce functions are all examples of Higher-order functions. In this post, you will learn about decorators and nested functions.

Nested Function

To understand Higher-order functions, you need to know about nested functions. A nested function is a function within a function. The purpose of nested functions is to hide functionality from the global scope. The inner function cannot be called outside of the function.

The following is example on how to create a nested function.

def outer_func(msg):

    def inner_func():
        print(msg)

    return inner_func


# Output: Hello Word
hello_word = outer_func("Hello World")
hello_word()


Enter fullscreen mode Exit fullscreen mode

You see, the outer function returns the inner function, and the variable "hello_word" is bound by that function. If you would call the inner function outside of the outer, you will receive an error.

Decorator

A decorator is a simple way to pass a function as a parameter. A benefit of decorators is that it adds functionality to existing functions. Another benefit because it makes your code readable or pythonic.

The following is an example of how to use a decorator.

def double(f):

    def inner_func(*args):

        result = f(*args) * 2

        return  result


    return inner_func


@double
def add(x,y):

    return  x + y

@double
def subtract(x,y):

    return  x - y

#Output: 6
result = add(1,2)

print(result)

#Output: 8
result = subtract(5,1)

print(result)
Enter fullscreen mode Exit fullscreen mode

Just like our previous example, the outer function returns the inner function. The annotation is used to call the outer function while the function below is passed as a parameter. A parameter inside the inner function is the same as a parameter in the function it decorates. Adding a * to your parameter allows your function to take varying inputs.

Discussion (0)