Passing Mechanism#
Python is often mistakenly described as “call by reference.” In reality, Python uses pass-by-object-reference (or pass-by-assignment).
Core Principles#
- Mutable Modification: If you pass a mutable object (eg. a class instance) and modify its fields, the change is reflected in the caller.
- Reassignment: If you reassign the parameter itself to a new object, the change is not reflected in the caller.
- None: Passing
Noneand reassigning the parameter doesn’t modify the variable in the calling function.
Mechanism#
Every class instance is implemented as a pointer. When an instance is passed to a function, the pointer is copied.
- Since both the caller and the function refer to the same memory, changes to fields are visible to both.
- Reassigning the parameter simply points the local name to a new memory location, leaving the caller’s pointer unchanged.
eg.
class Foo:
def __init__(self, x):
self.x = x
def inner1(f):
f.x = 20 # Modifies original instance
def inner2(f):
f = Foo(30) # Reassigns local pointer
def outer():
f = Foo(10)
inner1(f)
print(f.x) # 20
inner2(f)
print(f.x) # 20 (not 30)
g = None
inner2(g)
print(g is None) # True
outer()