Sub topic 8
What happens to an argument when you pass it
This chapter assumes you can define and call a function, you know the difference between a parameter and an argument, and you know which built-in types can change after creation (lists, dictionaries) and which cannot (numbers, strings, tuples). The rules here explain a common surprise: sometimes a function changes the caller's data, and sometimes it doesn't.
Python passes object references
When you call a function, Python does not copy the argument, and it does not hand over the caller's variable. It binds the parameter name to the same object that the argument expression produced. Both names then refer to one object.
People describe this as "pass by object reference" or "pass by assignment". Calling f(x) behaves like running param = x at the top of f. Everything you know about assignment applies to parameter passing.
You can check this with the is operator, which tests whether two names refer to the same object:
items = [1, 2]
def is_same(param):
return param is items
print(is_same(items)) # True
print(is_same(list(items))) # False, list() builds a new objectThe first call passes the original object, so the parameter and the global name match. The second call passes a new list with equal contents, which is a different object.
Two operations: rebinding and mutation
Once a function has a reference, it can do one of two different things with it.
- Rebinding points the parameter name at a different object. This only changes the function's local name. The caller's variable is untouched.
- Mutation changes the contents of the shared object in place. The caller sees the change because the caller's name refers to that same object.
Rebinding never reaches the caller
def add_one(x):
x = x + 1 # builds a new int and rebinds the local name x
return x
n = 10
print(add_one(n)) # 11
print(n) # 10Integers cannot be changed in place, so x + 1 must create a new object. The local name x then points to it. The caller's n still points to the original 10.
Rebinding also happens when the new value is a list:
def replace(tags):
tags = ["x"] # rebinds the local name only
return tags
original = ["a"]
replace(original)
print(original) # ['a']The assignment tags = ["x"] does not modify the list that original refers to. It disconnects the local name from it.
Mutation is visible to the caller
def add_tag(tags):
tags.append("new") # changes the shared list in place
data = ["a"]
add_tag(data)
print(data) # ['a', 'new']No assignment to tags happens here. The method call changes the object that both names share, so data shows the new element. The same applies to dictionaries (d["k"] = v, d.update(...)), sets (s.add(...)) and any object whose methods change its own state.
Summary table
| Statement inside the function | Effect on the caller's object |
|---|---|
| `param = something_new` | None. Only the local name changes. |
| `param.append(x)`, `param.sort()` | Changes the shared list. |
| `param[0] = x` | Changes the shared list or dictionary. |
| `param += other` on a list | Changes the shared list in place. |
| `param += other` on a tuple, string or number | None. A new object is built and the local name is rebound. |
The `+=` trap
The augmented assignment += looks like one operation, but its behavior depends on the type. For a list, += calls an in-place extend. For immutable types, no in-place version exists, so Python builds a new object and rebinds the name.
def grow(seq):
seq += [4]
numbers = [1, 2, 3]
grow(numbers)
print(numbers) # [1, 2, 3, 4]
def grow_tuple(seq):
seq += (4,)
return seq
point = (1, 2, 3)
print(grow_tuple(point)) # (1, 2, 3, 4)
print(point) # (1, 2, 3)The same line, seq += ..., changes the caller's list in the first function and leaves the caller's tuple alone in the second. By contrast, seq = seq + [4] on a list builds a new list and rebinds, so the caller would not see a change.
Local scope and the argument
Parameters are local variables. They exist only while the function runs, and each call gets fresh ones. This is why rebinding cannot leak out: the name x inside add_one is a different variable from any x in the caller, even if both are spelled the same.
What the local scope does not isolate is the object. A name is local, but the object it refers to may be shared with any number of other names, in this function, in the caller, or in a data structure that stored it earlier. Local scope limits names. It does not limit what you can do to a shared object.
Choosing between mutating and returning
A function that mutates its argument has a side effect. The earlier chapters on return values cover this idea. The argument-passing rules decide how you should design around it.
There are three common designs:
- Return a new value and leave the input alone. Callers can reuse their original data, and the function is easy to test.
- Mutate in place and return
None. This is the convention for built-in methods such aslist.sort()andlist.append(). TheNonereturn signals to the reader that the call changed something. - Copy first, then mutate the copy. This is useful when you want to work with a mutating algorithm but not change the caller's data.
Here is design 3:
def sorted_names(names):
names = list(names) # new list, local name rebound to the copy
names.sort() # mutates only the copy
return names
people = ["Zed", "Ada", "Max"]
print(sorted_names(people)) # ['Ada', 'Max', 'Zed']
print(people) # ['Zed', 'Ada', 'Max']The built-in sorted() works this way, while list.sort() follows design 2. Mixing the two conventions in one function is the usual source of bugs. A function that mutates its argument and also returns it invites callers to write result = f(data) and not realize that data changed too.
Shallow copies share inner objects
list(names), names.copy() and names[:] all make a shallow copy. The new outer list is separate, but its elements are the same objects as in the original. That is safe for a list of strings or numbers. It is not safe when the elements are mutable.
def touch_first_row(rows):
copy = list(rows)
copy[0].append(99) # the inner list is shared with the caller
return copy
grid = [[1], [2]]
touch_first_row(grid)
print(grid) # [[1, 99], [2]]For nested structures, use copy.deepcopy, which copies the whole tree of objects:
import copy
def touch_first_row_safely(rows):
clone = copy.deepcopy(rows)
clone[0].append(99)
return clone
grid = [[1], [2]]
print(touch_first_row_safely(grid)) # [[1, 99], [2]]
print(grid) # [[1], [2]]Deep copies cost time and memory proportional to the size of the structure. They can also fail on objects that cannot be copied, such as open files. Copy only when you need isolation, and copy as little as you can.
Common errors
- Expecting reassignment to modify the caller. Writing
data = []inside a function to "clear" the caller's list does nothing outside. Usedata.clear()if mutation is the goal, or return the new list. - Mutating an argument by accident. Calling
.sort(),.pop()or.update()on a parameter changes the caller's data. Check which methods mutate before using them on input. - Assuming a copy is deep. A shallow copy protects the outer container only.
- Returning the same object you were given and then mutating it. The caller ends up with two names for one object, which causes bugs far from the cause.
- Storing an argument inside a long-lived object. If a function saves
itemsin a class attribute or a global, later changes by the caller silently alter that stored data. Copy at the point of storing.
Connecting to default values
A default value is evaluated once, when def runs, and the resulting object is bound to the parameter every time the caller omits that argument. The next chapter shows why that is a problem when the default is a mutable object: every call shares one object, and mutation inside the function accumulates across calls. The idea of shared references from this chapter is the whole explanation.
Exercise
What do a and b contain after this code runs, and why?
def f(x, y):
x.append(1)
y = y + [1]
a = []
b = []
f(a, b)
Show answer
a is [1] and b is []. The call x.append(1) mutates the list shared by x and a, so the caller sees it. The expression y + [1] builds a new list, and the assignment rebinds only the local name y, so b still refers to its original empty list.
Exercise
The function below is meant to return a sorted copy but changes the caller's list. Which one-line change fixes it without changing the return value? def ordered(values): values.sort() return values
Show answer
Copy the list before sorting by adding values = list(values) as the first line of the body (or return sorted(values) instead of the two existing lines). The sort() call then changes only the local copy, and the caller's list keeps its order.
Exercise
A function receives a list of lists and must change one inner list without affecting the caller's data. Why is list(rows) not enough, and what should you use instead?
Show answer
list(rows) is a shallow copy. The new outer list holds the same inner list objects as the original, so changing an inner list also changes the caller's data. Use copy.deepcopy(rows) to copy the inner lists too.