Sub topic 1
Functions are values: passing and returning them
Prerequisites
This chapter assumes you can already do the following:
- Define and call functions with
def, including default values,*argsand**kwargs. - Work with lists, tuples and dictionaries.
- Read a list comprehension.
You don't need to know lambda yet. The next chapter introduces it. This chapter covers the idea underneath it: in Python, a function is an ordinary value.
What "first-class" means
A first-class object is a value you can handle like any other value. You can store it in a variable, put it in a collection, pass it to a function, and return it from a function. Python gives all of these abilities to functions.
When you run a def statement, Python builds a function object and binds it to a name. The name is just a label for the object, the same as a name bound to a list or a string.
def greet(name):
return f"Hello, {name}!"
print(type(greet)) # <class 'function'>
print(greet.__name__) # greet
say = greet
print(say("Ada")) # Hello, Ada!
print(say is greet) # TrueThe assignment say = greet does not copy anything. It adds a second name for the same object, so say is greet is True. Note the missing parentheses on the right side of the assignment.
The name versus the call
The most important habit in this chapter is to tell two expressions apart:
greetis the function object itself.greet("Ada")runs the function and produces its return value.
Parentheses mean "call it now". Leaving them off means "refer to it". Every higher-order technique in this tutorial depends on this difference.
| Expression | What it is | Type of the result |
|---|---|---|
| `greet` | The function object | `function` |
| `greet("Ada")` | The value returned by a call | `str` |
| `greet.__name__` | An attribute of the function object | `str` |
Functions in collections: dispatch tables
Because a function is a value, a dictionary can hold functions as its values. This pattern is called a dispatch table. It replaces a long chain of if and elif statements with a lookup.
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
operations = {"add": add, "sub": sub, "mul": mul}
def calculate(op_name, a, b):
try:
func = operations[op_name]
except KeyError:
raise ValueError(f"unknown operation: {op_name}") from None
return func(a, b)
print(calculate("add", 4, 5)) # 9
print(calculate("mul", 4, 5)) # 20The dictionary stores add, not add(...). Nothing runs when the dictionary is built. The call happens later, in func(a, b).
Adding a new operation means adding one entry. The calculate function does not change.
Passing functions as arguments
A function that takes another function as an argument, returns one, or does both is a higher-order function. The function you pass in is often called a callback.
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, "hi")) # HIapply_twice knows nothing about what func does. It only relies on one promise: func accepts one argument and returns something that func can accept again. This separation is the main benefit of higher-order functions. One piece of code controls how and when to call, and another piece decides what to do.
Built-in functions and methods work here too. str.upper is a function object, so you can pass it around like add_three.
Passing a function whose signature does not fit is a common error. apply_twice(len, "abc") fails with a TypeError. The first call returns 3, and the second call tries len(3). Python does not check the shape of a callback when you pass it. The error appears only when the callback is called.
Passing the function, not its result
The easiest mistake is to add parentheses by habit.
def shout(text):
return text.upper()
words = ["ant", "bee"]
print(list(map(shout, words))) # ['ANT', 'BEE']map is a built-in higher-order function. It calls its first argument once for each item in the second. The next chapters cover it in detail. Here, note what map(shout, words) receives: the function itself.
If you wrote map(shout("ant"), words), Python would first call shout("ant") and get the string "ANT". Then map would try to call that string for each item. Because map is lazy, the error TypeError: 'str' object is not callable appears only when you consume the result, for example with list(...).
Returning functions
A function can build a new function and return it. The inner def runs each time the outer function is called, so each call creates a separate function object.
def make_greeter(greeting):
def greeter(name):
return f"{greeting}, {name}!"
return greeter
hello = make_greeter("Hello")
hi = make_greeter("Hi")
print(hello("Ada")) # Hello, Ada!
print(hi("Bob")) # Hi, Bob!
print(make_greeter("Hey")("Cy")) # Hey, Cy!
print(hello is hi) # FalseTwo things are worth noticing here.
greeterusesgreeting, a variable that belongs tomake_greeter. Aftermake_greeterreturns, that call is finished, yethellostill knows its greeting. A function that remembers variables from the scope where it was created is a closure. A later chapter explains how closures work and what can go wrong with them.- The last line calls the result of a call:
make_greeter("Hey")returns a function, and("Cy")calls it immediately.
The diagram shows the flow of values in the three situations covered so far.
Which things are callable
Python lets you call any object that is callable. The built-in callable() tells you whether an object can be called. Functions, methods, built-ins and classes are all callable. An instance is callable if its class defines __call__.
class Counter:
def __init__(self):
self.count = 0
def __call__(self):
self.count += 1
return self.count
c = Counter()
print(callable(c), callable(len), callable(42)) # True True False
print(c(), c()) # 1 2
print(callable(Counter)) # TrueThis matters because a higher-order function usually accepts any callable, not only a function made with def. A class, a bound method, or an object with __call__ can all be passed where a callback is expected. Unlike a plain function, a Counter object can keep state between calls.
Functions have attributes
A function is an object, so it can hold attributes. Python itself stores several, such as __name__ and __doc__.
def slow_square(n):
"""Return n squared."""
slow_square.calls += 1
return n * n
slow_square.calls = 0
slow_square(3)
slow_square(4)
print(slow_square.calls) # 2
print(slow_square.__doc__) # Return n squared.Attaching your own attributes works, but it is rarely the clearest design. A class or a closure is usually easier to read. The main reason to know about attributes is that decorators, covered later, must copy __name__ and __doc__ when they wrap a function.
Edge cases and common errors
- Missing return value. A function without a
returnstatement gives backNone. Passing the result of such a call, such asprint, where a function is expected givesTypeError: 'NoneType' object is not callable. - Rebinding a name. Names can be reassigned, so
len = 5hides the built-in function. Later calls tolen(...)fail. Treat function names as ordinary variables when you pick names. - Equality. Two functions with the same code are still different objects.
==on functions compares identity, so it does not tell you whether they behave the same way. - Argument mismatch. The caller has to match the callback's signature. If
sorted,mapor your own code passes one argument, a callback written for two fails when called. - Dispatch on missing keys. A plain
operations[name]raisesKeyErrorwhen the name is missing. Decide whether to catch it, ascalculatedoes, or to useoperations.get(name)and handleNone.
Summary of the working model
defcreates a function object and binds a name to it.- The name refers to the object. Parentheses call it.
- Because the object is a value, you can store it, pass it, and return it.
- A function that accepts or returns functions is higher-order.
- A function created inside another function can remember variables from that outer call.
Exercise
A learner writes result = sorted(words, key=len()) and gets a TypeError. What is wrong, and how do they fix it?
Show answer
len() calls the function with no arguments, which fails because len requires one. The key parameter expects the function object, not a call. The fix is sorted(words, key=len). Python then calls len once for each item.
Exercise
Write a function make_power(exponent) that returns a function raising its argument to that exponent. What does make_power(3)(2) give, and how many function objects are created by make_power(2) and make_power(3) together?
Show answer
Define an inner function power(x) that returns x ** exponent, and have make_power return power without calling it. The result of make_power(3)(2) is 8. Each call to make_power runs the inner def again, so two calls create two separate function objects, and each remembers its own exponent.