Function Parameters as References

Posted April 27, 2021 by clannadzsy  ‐  1 min read

This example uses only the standard library and was checked with CPython 3.12.14. Save the complete block as references.py and run python references.py; each call prints its return value followed by the original arguments.

Python passes arguments by assignment: the parameter initially refers to the same object as the caller’s argument. Rebinding a local parameter does not rebind the caller’s variable. Mutating a shared list does change the object both names refer to, as explained in the Python FAQ.

"""
from Fluent Python 2nd Example 6-11
"""

def f(p1, p2):
    p1 += p2
    return p1

x, y = 1, 2
print(f(x, y))
print(x, y)
# 3
# 1 2

a = [1, 2]
b = [3, 4]
print(f(a, b))
print(a, b)
# [1, 2, 3, 4]
# [1, 2, 3, 4] [3, 4]

m = (1, 2)
n = (3, 4)
print(f(m, n))
print(m, n)
# (1, 2, 3, 4)
# (1, 2) (3, 4)

For these built-in types, += extends the list in place, while integers and tuples produce a new result that is assigned to the local name p1. The return value therefore differs from the caller’s unchanged number or tuple. Other classes can define their own augmented-assignment behavior.