Sub topic 12
Returning results versus changing state
This chapter assumes you can define a function with def, use return, and work with lists. It also assumes you know that Python passes arguments as references to objects. Here you will learn the difference between a function that returns a result and a function that changes something outside itself.
Two ways a function can have an effect
A function can affect the program in two ways:
- It returns a result. The caller receives a value and decides what to do with it.
- It causes a side effect. It changes something that exists outside the function, such as a list passed in, a file, or the screen.
Printing is a side effect. A function that only prints returns None, so the caller cannot use its output.
Changing the argument in place
Because arguments are object references, a function that mutates a list changes the caller's list too.
def add_tax_in_place(prices, rate):
for i in range(len(prices)):
prices[i] = prices[i] * (1 + rate)
cart = [100, 40]
add_tax_in_place(cart, 0.25)
print(cart) # [125.0, 50.0]The original cart is gone. Anyone else holding a reference to that list sees the change as well. The function returns None, so nothing in the call itself shows that the list was modified.
Returning a new value instead
The alternative builds a new object and returns it.
def with_tax(prices, rate):
return [p * (1 + rate) for p in prices]
cart = [100, 40]
taxed = with_tax(cart, 0.25)
print(cart) # [100, 40]
print(taxed) # [125.0, 50.0]The caller keeps both versions and can see where the new value comes from. This function is also easier to test. You call it with an input and compare the output, with no state to set up or inspect afterward.
A common error: using the result of a mutating method
Many built-in methods change an object and return None. Assigning their result is a frequent bug.
numbers = [3, 1, 2]
result = numbers.sort()
print(result) # None
print(numbers) # [1, 2, 3]
original = [3, 1, 2]
ordered = sorted(original)
print(original) # [3, 1, 2]
print(ordered) # [1, 2, 3]list.sort() changes the list in place. sorted() returns a new list. Python's built-ins follow this pattern: a method that mutates returns None, and a function that builds a new object returns it.
Choosing between them
| Situation | Prefer |
|---|---|
| Computing a value from inputs | Return the value |
| The caller might need the original data later | Return a new object |
| The point of the function is the effect (save a file, print, update a database) | Side effect, documented clearly |
| Copying a very large structure would be too slow or use too much memory | Mutate in place and name the function to show it |
A useful rule is to separate the two jobs. Put calculations in functions that return results. Put output and storage in small functions at the edges of your program that do the printing or saving.
def total(prices, rate):
return sum(prices) * (1 + rate)
def report(prices, rate):
print(f"Total: {total(prices, rate):.2f}")
report([100, 40], 0.25) # Total: 175.00total can be tested and reused. report is the only function that touches the screen.
If a function must mutate its argument, say so in its name and docstring. Names like add_tax_in_place or append_log tell the caller what to expect.
Exercise
What do a and b contain after this code runs, and why?
def doubleall(values):
for i in range(len(values)):
values[i] *= 2
a = [1, 2, 3]
b = doubleall(a)
Show answer
a is [2, 4, 6] and b is None. The function mutates the list it receives, which is the same object as a. It has no return statement, so it returns None, and that value is assigned to b.