Sub topic 1
Functions are values: passing and returning them
Prerequisites
This chapter assumes you can define and call functions with def, and that you know lists, tuples, and dictionaries. You should also be comfortable with default values, *args, and **kwargs. Lambdas are not needed yet. They come in the next chapter.
Functions are objects
In Python, a def statement creates a function object and binds it to a name. The name works like any other variable. The function is a value, so you can assign it, store it, pass it, and return it. Languages that allow this are said to have first-class functions.
def shout(text):
return text.upper() + "!"
print(type(shout)) # <class 'function'>
speak = shout # a second name for the same object
print(speak("hi")) # HI!
print(speak is shout) # TrueWriting shout refers to the function. Writing shout("hi") calls it. Mixing these up is the most common mistake in this area.
Storing functions in data structures
Because a function is a value, it can sit in a list or a dictionary. A dictionary of functions is a clean replacement for a long if/elif chain.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
operations = {"add": add, "subtract": subtract}
name = "subtract"
print(operations[name](10, 4)) # 6The expression operations[name] looks up the function. The parentheses after it call it.
Passing a function as an argument
A function that takes another function as an argument, or returns one, is a higher-order function. The built-in sorted is an example. Here is a small one of our own.
def apply_twice(func, value):
return func(func(value))
def add_three(n):
return n + 3
print(apply_twice(add_three, 10)) # 16apply_twice does not know what func does. It only knows that func can be called with one argument. This is what makes higher-order functions reusable: the caller supplies the behavior.
Returning a function
A function can build and return another function. The inner function is created each time the outer one runs.
def make_greeter(greeting):
def greet(name):
return f"{greeting}, {name}!"
return greet
hello = make_greeter("Hello")
print(hello("Ada")) # Hello, Ada!The returned greet still uses greeting, even though make_greeter has finished. That is a closure, and a later chapter explains how it works.
Common errors
Two other points are worth checking when something fails:
- A function with no
returnstatement returnsNone. Passing that result where a function is expected givesTypeError: 'NoneType' object is not callable. - Two names can refer to one function. Reassigning
speakdoes not changeshout.
Why this matters
Everything later in this tutorial builds on this idea. Key functions for sorted, map and filter, closures, functools.partial, and decorators all pass functions around as ordinary values. A lambda is a shorter way to write the function you pass.
Exercise
What is the difference between apply_twice(add_three, 10) and apply_twice(add_three(5), 10)? Which one fails, and what is the error?
Show answer
The first passes the function object add_three, so apply_twice can call it twice and returns 16. The second calls add_three(5) first, which returns the integer 8, and passes 8 as func. When apply_twice runs func(func(value)), Python tries to call an integer and raises TypeError: 'int' object is not callable.
Exercise
Write a function make_adder(n) that returns a function adding n to its argument. What does make_adder(5)(2) return?
Show answer
def makeadder(n):
def adder(x):
return x + n
return adder
`makeadder(5)(2) returns 7. The call make_adder(5)` returns the inner function, and the second pair of parentheses calls it with 2.