Sub topic 1
Functions are objects you can pass around
Prerequisites
This chapter assumes you can already do the following:
- Define and call Python functions, including functions with positional and keyword arguments.
- Read basic Python classes and methods.
- Use
importto load modules from the standard library.
You do not need to know anything about decorators yet. This chapter builds the first idea they rest on: in Python, a function is a value like any other.
The core idea
A def statement does two things. It creates a function object, and it binds a name to that object. The name is just a label. The object holds the code, the default values, and some metadata.
Because the function is an object, you can do with it what you do with any other object:
- assign it to another name,
- store it in a list or dictionary,
- pass it as an argument,
- return it from another function.
Languages that allow all four call their functions first-class. Decorators are built entirely from these abilities.
def greet(name):
return f"Hello, {name}!"
say_hello = greet # no parentheses: no call, just a second name
print(say_hello("Ada")) # Hello, Ada!
print(say_hello is greet) # True
print(type(greet)) # <class 'function'>Notice the difference between greet and greet(...). The bare name refers to the function object. Adding parentheses with arguments calls it and gives you its return value. Forgetting this difference is the most common early mistake with decorators.
Functions have attributes
A function object has attributes you can inspect. Two of them matter later in this tutorial.
def add(a, b):
"""Return the sum of a and b."""
return a + b
print(add.__name__) # add
print(add.__doc__) # Return the sum of a and b.
add.calls = 0 # you can even attach your own attributes
print(add.calls) # 0__name__ and __doc__ are what tools, debuggers and help() show. A later chapter on functools.wraps explains why decorators must take care to keep them.
Storing functions in data structures
Since functions are values, a dictionary can map keys to behavior. This is a common replacement for a long if/elif chain.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
OPERATIONS = {
"+": add,
"-": subtract,
"*": multiply,
}
def calculate(a, symbol, b):
operation = OPERATIONS[symbol]
return operation(a, b)
print(calculate(6, "*", 7)) # 42
print(calculate(6, "-", 7)) # -1The dictionary holds the function objects themselves. Looking one up gives you a function, and you call it afterwards.
Passing functions as arguments
A function that accepts another function as a parameter is called a higher-order function. The built-ins sorted, map and filter are examples.
words = ["banana", "fig", "cherry", "kiwi"]
print(sorted(words, key=len)) # ['fig', 'kiwi', 'banana', 'cherry']
print(list(map(str.upper, words))) # ['BANANA', 'FIG', 'CHERRY', 'KIWI']
print(list(filter(lambda w: len(w) > 4, words))) # ['banana', 'cherry']You can write your own. The function below calls whatever function it is given, twice.
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.strip, " padded ")) # paddedapply_twice knows nothing about what func does. It only relies on func being callable with one argument. This separation of "when and how often to call" from "what to call" is exactly what a decorator does.
Returning functions from functions
A function can also build a new function and hand it back. The inner def runs each time the outer function runs, so every call produces a fresh function object.
def make_multiplier(n):
def multiply(x):
return x * n
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15
print(double is triple) # False
print(apply_twice(double, 3) if "apply_twice" in globals() else None)Look at what multiply does with n. The variable n is a parameter of make_multiplier, and that call has already finished by the time you call double(5). Yet double still knows that n is 2. This works through a closure, which the next chapter covers in detail. For now, accept that the inner function carries the values it needs with it.
Here is the complete example from the plan, with both ideas together:
def make_multiplier(n):
def multiply(x):
return x * n
return multiply
double = make_multiplier(2)
print(double(5)) # 10
def apply_twice(func, value):
return func(func(value))
print(apply_twice(double, 3)) # 12apply_twice(double, 3) computes double(double(3)), which is double(6), which is 12.
Callables: not only functions
Python code often needs "something I can call", not specifically a def function. Lambdas, built-in functions, bound methods, classes and instances that define __call__ are all callable. The built-in callable() tests for this.
class Adder:
def __init__(self, amount):
self.amount = amount
def __call__(self, x):
return x + self.amount
add_ten = Adder(10)
print(callable(add_ten)) # True
print(callable(len)) # True
print(callable(42)) # False
print(apply_twice(add_ten, 1)) # 21Here apply_twice works with an object of a class, because the instance is callable. Later chapters use this to write class-based decorators that keep state.
Edge cases and gotchas
Names are looked up when the call runs
A function body is not evaluated when the function is defined. Names inside it are resolved when the function is called. This matters when you rebind a name.
def hello():
return "hello"
greeting = hello
def hello(): # rebinds the name hello to a new function
return "HELLO"
print(greeting()) # hello (the old object, still alive via greeting)
print(hello()) # HELLOThe old function object is not destroyed because greeting still refers to it. Rebinding a name never changes the object it used to point to. This is the mechanism behind the @ syntax, which reassigns a function's name to a new, wrapped function.
Methods are functions bound to an object
A function defined in a class body is an ordinary function. When you access it through an instance, Python produces a bound method that remembers the instance and passes it as self.
class Counter:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
return self.value
c = Counter()
step = c.increment # bound method object
print(step()) # 1
print(step()) # 2
print(Counter.increment(c)) # 3 (same function, called explicitly)Storing c.increment in a variable keeps the link to c. This is helpful for callbacks. It also means a stored bound method keeps its instance alive.
Lambdas are functions with one expression
A lambda creates a function object whose body is a single expression. It has no statements and its __name__ is <lambda>, which makes tracebacks harder to read. Prefer def when the function is reused or needs a name.
Calling too early
def get_value():
return 5
result = get_value() # result is 5, an int
# result() # TypeError: 'int' object is not callable
callback = get_value # callback is the function
print(callback()) # 5When an API wants a function, such as a callback, pass get_value, not get_value(). The second form passes the result of the call. You will see this again as a pitfall when decorators take arguments.
Comparing the four abilities
| Ability | Example | Why decorators need it |
|---|---|---|
| Assign to a name | `say_hello = greet` | `@` rebinds the function's name to the result |
| Store in a data structure | `OPERATIONS["+"] = add` | Registries of decorated functions |
| Pass as an argument | `apply_twice(add_three, 10)` | A decorator receives the function it wraps |
| Return from a function | `return multiply` | A decorator returns the replacement function |
Where this leads
A decorator is a function that takes a function and returns a function. You now have every piece except one: how the returned inner function keeps access to variables from the enclosing call. The next chapter explains that with closures.
Exercise
Write a function compose(f, g) that returns a new function. Calling the new function with x must return f(g(x)). Then use it to build inc_then_double from inc = lambda x: x + 1 and double = lambda x: x * 2, so that double(inc(x)) is computed. What does inc_then_double(4) return?
Show answer
``python is not allowed inside an answer, so in words and plain code: define def compose(f, g): with an inner def composed(x): return f(g(x)) and return composed. To get double applied after inc, call compose(double, inc). Then incthendouble(4) computes double(inc(4)), which is double(5), which is 10. Note the argument order: the function applied last comes first in compose(f, g)`.
Exercise
A learner writes handlers = {"a": get_a(), "b": get_b()} and later calls handlers["a"](), getting TypeError: 'int' object is not callable. What is wrong and how do you fix it?
Show answer
The parentheses call get_a and get_b while the dictionary is being built, so the dictionary stores their return values (here an int), not the functions. Remove the parentheses: handlers = {"a": get_a, "b": get_b}. Then handlers["a"]() calls the function.