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..