Sub topic 1
Functions are objects you can pass around
Prerequisites
This chapter assumes you can define and call Python functions, and that you know positional and keyword arguments. You should also be able to import from the standard library. Basic classes are only needed in later chapters.
Why start here
A decorator is a function that takes another function and returns a function. That only works because Python treats functions as ordinary values. This chapter covers that idea, which later chapters build on.
A function is a value
When you write def, Python creates a function object and binds it to a name. The name is a variable like any other. You can assign the object to another name, store it in a list or dictionary, and inspect it.
def square(x):
return x * x
alias = square
print(alias(4)) # 16
print(alias is square) # True
print(type(square)) # <class 'function'>
print(square.__name__) # square
operations = {"square": square, "negate": lambda x: -x}
print(operations["square"](5)) # 25Calling a function needs parentheses. Writing square without them refers to the object. Writing square(4) runs it. Mixing these up is a common source of bugs.
Passing functions as arguments
Because a function is a value, another function can receive it as a parameter. The receiving function decides when, and whether, to call it.
def apply_twice(func, value):
return func(func(value))
def add_three(x):
return x + 3
print(apply_twice(add_three, 10)) # 16
print(apply_twice(str.upper, "a")) # ABuilt-ins use this pattern too. sorted(words, key=len) passes the function len without calling it. sorted calls it once for each item.
Returning functions from functions
A function can also build and return a new function. The inner function keeps access to variables from the enclosing function. That retained access is a closure, which the next chapter covers in detail.
def make_multiplier(n):
def multiply(x):
return x * n
return multiply
double = make_multiplier(2)
print(double(5)) # 10
print(apply_twice(double, 3)) # 12Each call to make_multiplier creates a separate multiply function with its own n. double remembers n = 2 after make_multiplier has returned.
The link to decorators
Three abilities from this chapter combine to make decorators:
- A function can be passed as an argument.
- A function can create and return another function.
- The returned function can still use the argument it was given.
A decorator receives your function, builds a wrapper around it, and returns the wrapper. Everything else in this tutorial is syntax and detail on top of that pattern.
Common errors
- Calling when you meant to pass.
apply_twice(add_three(1), 10)passes the number 4, not the function, and fails withTypeError: 'int' object is not callable. - Forgetting to return the inner function. If
make_multiplierends withoutreturn multiply,doubleisNone, and calling it raisesTypeError. - Returning the call. Writing
return multiply(2)returns a number, not a function.
Exercise
Write a function compose(f, g) that returns a new function which applies g first and then f. Then show what compose(str, abs)(-7) returns.
Show answer
def compose(f, g): def composed(x): return f(g(x)) return composed print(compose(str, abs)(-7)) # 7 (the string "7") compose takes two functions as arguments and returns a new inner function. abs(-7) gives 7, and str(7) gives the string "7".
Exercise
Why does sorted(words, key=len()) raise an error while sorted(words, key=len) works?
Show answer
len() calls the function with no arguments, which raises a TypeError before sorted runs. len without parentheses is the function object, which sorted calls once per item.