Sub topic 12
Returning Results Versus Changing State
This chapter assumes you can define a function with def, pass arguments by position and keyword, and use return. You should also know that lists and dictionaries can be changed after they are created. Here you will learn the difference between a function that hands back a result and a function that changes something outside itself. You will also learn how to choose between the two.
Two ways a function can have an effect
A function can affect the program in two ways:
- It can return a value. The caller receives the value and decides what to do with it.
- It can cause a side effect. A side effect is any change a function makes that is visible outside the function, other than its return value.
Common side effects include:
- printing to the screen
- writing a file
- changing a list or dictionary that was passed in
- changing a global variable
- sending a network request
Many functions do only one of these. Some do both. Problems start when you expect one and get the other.
Printing is not returning
The most common mix-up is using print where return is needed. Both put a value in front of you when you run the code in a terminal, so they look the same there.
def double_print(n):
print(n * 2)
def double_return(n):
return n * 2
a = double_print(4) # prints 8
b = double_return(4) # prints nothing
print(a) # None
print(b) # 8
print(b + 1) # 9double_print writes 8 to the screen, but its return value is None. The program cannot use that 8 afterwards. Running a + 1 would raise a TypeError. double_return gives the caller a real value that can be stored, added to or passed to another function.
Return the result and let the caller decide whether to print it. The same function then works in a script, a test and a web page.
Functions that change their arguments
In an earlier chapter you saw that Python passes object references. A function receives a reference to the same object the caller has. If the object is mutable, such as a list, dictionary or set, the function can change it, and the caller sees the change.
def add_tax_in_place(prices, rate):
for i in range(len(prices)):
prices[i] = round(prices[i] * (1 + rate), 2)
def with_tax(prices, rate):
return [round(p * (1 + rate), 2) for p in prices]
prices = [10.0, 20.0]
print(with_tax(prices, 0.1)) # [11.0, 22.0]
print(prices) # [10.0, 20.0] (unchanged)
add_tax_in_place(prices, 0.1)
print(prices) # [11.0, 22.0] (changed)Both functions compute the same numbers. They differ in what the caller is left with:
with_taxbuilds a new list and leaves the original alone.add_tax_in_placeoverwrites the original and returnsNone.
Python's built-in types follow the same split. Methods that change an object in place, such as list.sort(), list.append() and list.reverse(), return None. Functions and methods that build a new object, such as sorted() and str.upper(), return that object.
numbers = [3, 1, 2]
result = numbers.sort()
print(result) # None
print(numbers) # [1, 2, 3]
numbers = [3, 1, 2]
print(sorted(numbers)) # [1, 2, 3]
print(numbers) # [3, 1, 2]Writing numbers = numbers.sort() is a classic bug. It replaces your list with None.
Rebinding is not mutation
Changing an object and rebinding a name are different operations. Inside a function, a parameter is a local name. If you assign a new object to it, you only change what that local name points to.
def clear_wrong(items):
items = [] # rebinds the local name only
def clear_right(items):
items.clear() # mutates the caller's list
data = [1, 2, 3]
clear_wrong(data)
print(data) # [1, 2, 3]
clear_right(data)
print(data) # []The same rule applies to +=. For a list, items += [4] mutates the list in place, so the caller sees it. For a number or string, += creates a new object and rebinds the local name, so the caller does not see it. When code behaves differently for lists and numbers, this is usually the reason.
def grow_list(items):
items += [99]
def grow_number(n):
n += 99
values = [1]
count = 1
grow_list(values)
grow_number(count)
print(values) # [1, 99]
print(count) # 1Comparing the styles
| Style | What the caller gets | Typical return value | Example |
|---|---|---|---|
| Pure function | A new result, with nothing else changed | The result | `sorted(xs)` |
| In-place mutation | The same object, modified | `None` | `xs.sort()` |
| Output only | Text on screen or in a file | `None` | `print(x)` |
| Mixed | Both a result and a changed object | The result | `xs.pop()` |
A pure function returns a value that depends only on its arguments, and it causes no side effects. Calling it twice with the same arguments gives the same answer. Pure functions are the easiest kind to test and reason about.
def apply_discount(price, percent):
return round(price * (1 - percent / 100), 2)
assert apply_discount(80.0, 25) == 60.0
assert apply_discount(80.0, 25) == 60.0 # same input, same outputMixed functions are not wrong. list.pop() removes an item and returns it, and that is exactly why it is useful. If you write a mixed function, make both effects obvious in its name and docstring.
Choosing between returning and mutating
Prefer returning a new value when:
- the data is small enough that copying it is cheap
- the caller may still need the original
- you want to test the function with simple assertions
- the function may be called from several places
Prefer mutating in place when:
- the object is large and copying would waste time or memory
- the function's purpose is to update shared state, such as a cache or a settings dictionary
- you follow a convention that the function name makes clear, such as
sort_in_placeorupdate_totals
If you do mutate an argument, return None and say so. Mutating an argument and also returning it invites confusion, because the caller may think they received a copy.
Protecting the caller's data
Sometimes you want to work on a list inside a function without altering the caller's list. Copy it first.
def normalized(values):
"""Return a sorted copy of values without changing the original."""
result = list(values) # shallow copy
result.sort()
return result
original = [3, 1, 2]
print(normalized(original)) # [1, 2, 3]
print(original) # [3, 1, 2]list(values) is a shallow copy. It creates a new outer list, but the elements inside are the same objects. If the elements are themselves mutable, such as lists inside a list, changing them still affects the caller. For nested data, use copy.deepcopy.
import copy
def mark_done(tasks):
"""Return a copy of tasks with every task marked done."""
updated = copy.deepcopy(tasks)
for task in updated:
task["done"] = True
return updated
tasks = [{"name": "write", "done": False}]
print(mark_done(tasks)) # [{'name': 'write', 'done': True}]
print(tasks) # [{'name': 'write', 'done': False}]With list(tasks) instead of copy.deepcopy(tasks), the original task dictionaries would be changed too.
Hidden side effects
The side effects that cause the most trouble are the ones nobody expected. Watch for these:
- Global variables. A function that reads or writes a global gives different results depending on program state. Pass the value in as a parameter instead.
- Mutable defaults. As you saw earlier, a default list shared between calls is a hidden side effect that builds up over time.
- Mutated arguments. A helper that sorts or edits the list it receives can break the caller several lines later, in code that looks unrelated.
- Input and output buried in logic. A function that calculates a total and also prints it cannot be reused where printing is unwanted.
A good habit is to keep calculation and output in separate functions:
def total_price(prices, tax_rate):
return round(sum(prices) * (1 + tax_rate), 2)
def print_receipt(prices, tax_rate):
total = total_price(prices, tax_rate)
print(f"Total: {total:.2f}")
print_receipt([10.0, 5.5], 0.2) # Total: 18.60total_price can be tested with assert. print_receipt is a thin layer around it that handles the output.
How the data flows
The diagram below shows the two paths a function can take with a mutable argument.
Common mistakes
- Using the return value of an in-place method.
x = items.sort()makesxequal toNone. - Expecting reassignment to reach the caller.
items = []inside a function does not empty the caller's list. - Forgetting that a function returns
Noneby default. If a branch of anifhas noreturn, that path producesNone. The surprise often shows up later as'NoneType' object has no attribute .... - Mutating an argument and also returning it. The caller cannot tell whether the result is a copy.
- Using a shallow copy on nested data. Inner objects are still shared.
Exercises
Exercise
What do result and numbers contain after running this code, and why?
numbers = [5, 2, 9]
result = numbers.reverse()
Show answer
result is None and numbers is [9, 2, 5]. list.reverse() changes the list in place and returns None, so assigning its return value gives None. To get a reversed copy and keep the original, use reversed_copy = numbers[::-1] or list(reversed(numbers)).
Exercise
Rewrite this function so it no longer changes the list it receives and returns the result instead. def remove_negatives(values): for v in values[:]: if v < 0: values.remove(v)
Show answer
Build and return a new list.
def removenegatives(values):
return [v for v in values if v >= 0]
The original list is untouched, and the function now returns a usable result. Calling `removenegatives([3, -1, 4, -5]) gives [3, 4]`.
Exercise
Explain why grow_list changes the caller's list but grow_number does not.
def growlist(items):
items += [1]
def grownumber(n):
n += 1
Show answer
A list is mutable, and += on a list extends the same object in place, so the caller's reference sees the change. A number is immutable, so n += 1 creates a new integer and rebinds only the local name n. The caller's number keeps its old value.