What is the difference between higher order functions and decorators?

Viewed 1978

I do understand that higher order functions are functions that take functions as parameters or return functions. I also know that decorators are functions that add some functionality to other functions. What are they exactly. Are they the functions that are passed in as parameters or are they the higher order functions themselves?

note: if you will give an example give it in python

2 Answers

A higher order function is a function that takes a function as an argument OR* returns a function.

A decorator in Python is (typically) an example of a higher-order function, but there are decorators that aren't (class decorators**, and decorators that aren't functions), and there are higher-order functions that aren't decorators, for example those that take two required arguments that are functions.

Not decorator, not higher-order function:

def hello(who):
    print("Hello", who)

Not decorator, but higher-order function:

def compose(f, g):
    def wrapper(*args, **kwargs):
        return g(f(*args, **kwargs))
    return wrapper

Decorator, not higher-order function:

def classdeco(cls):
    cls.__repr__ = lambda self: "WAT"
    return cls

# Usage:
@classdeco
class Foo:
    pass

Decorator, higher-order function:

def log_calls(fn):
    def wrapper(*args, **kwargs):
        print("Calling", fn.__name__)
        return fn(*args, **kwargs)
    return wrapper

* Not XOR
** Whether or not you consider class decorators to be higher-order functions, because classes are callable etc. is up for debate, I guess..

A higher-order function is a function that either takes a function as an argument or returns a function.

Decorator syntax is a syntactic shortcut:

@f
def g(...):
    ...

is just a convenient shorthand for

def g(...):
    ...
g = f(g)

As such, a decorator really is simply a function that takes another function as an argument. It would be more accurate to talk about using f as a decorator than to say that f is a decorator.

Related