@MZeeshanM to PythonEnglish • 6 days ago

Does Python pass arguments by reference or by object reference?

message-square
0
1
Does Python pass arguments by reference or by object reference?
@MZeeshanM to PythonEnglish • 6 days ago

Python passes arguments by object reference (also formally called pass-by-assignment or call-by-sharing)—meaning the function parameter receives a new local reference pointing to the exact same object in memory as the caller’s argument, rather than copying the object (pass-by-value) or aliasing the caller’s variable binding itself (true C+±style pass-by-reference).

Basic Example

# 1. MUTABLE OBJECT (e.g., list, dict, set):
# In-place mutations through the parameter affect the caller's object
def add_item(items: list[str]) -> None:
    items.append("banana")  # Mutates the shared list object in place

fruits = ["apple"]
add_item(fruits)
print(fruits)  # Output: ['apple', 'banana']


# 2. REASSIGNMENT (for BOTH mutable and immutable objects):
# Rebinding the parameter '=' only changes the local variable, NOT the caller's variable
def reassign_values(num: int, items: list[str]) -> None:
    num = 999                 # Points local 'num' to a new int object
    items = ["completely_new"]  # Points local 'items' to a new list object

count = 10
my_list = ["original"]
reassign_values(count, my_list)

print(count)    # Output: 10 (unchanged)
print(my_list)  # Output: ['original'] (unchanged)

Key Details & Mechanics

  • Why Python is neither pure “pass-by-value” nor pure “pass-by-reference”:
    • Not pass-by-value: Passing a 10 million-element list or dict into a function does not copy its contents ($O(1)$ reference pass, id(param) == id(arg) inside the function).
    • Not C++/C# ref pass-by-reference: In C++ (void fn(int& x)), assigning x = 5 inside the function overwrites the caller’s variable binding directly. In Python, param = new_value simply rebinds the local parameter name to a different object in the function’s local namespace, leaving the caller’s variable pointing to the original object.
  • Mutable vs. Immutable behavior explained cleanly:
    • Immutable objects (int, float, str, tuple, bytes, frozenset): Because these objects cannot be modified in place, any operation like x += 1 or s += "!" creates a new object and rebinds the local variable—so the caller never sees a change.
    • Mutable objects (list, dict, set, custom class instances): Calling mutating methods (items.append(), d["k"] = v, items.sort(), items += [4]) modifies the underlying object in memory directly, which the caller sees immediately because both names reference the same id().
  • Beware of augmented assignment (+=) on lists vs. tuples: items += [4] on a list calls list.__iadd__(), mutating the list in place (visible to the caller), whereas t += (4,) on a tuple creates a new tuple and rebinds the local parameter (invisible to the caller).
  • How to prevent unintended side effects on mutable arguments: Pass a copy (fn(my_list.copy()) or copy.deepcopy(nested_data)) at the call site, or clone defensively inside the function (items = list(items)) before mutating.
  • How to “return” updated immutable values: Return the new object explicitly (count = increment(count)) or wrap state inside a mutable container (dict, list, or @dataclass instance).

Comparison of Argument-Passing Models

Model Mechanism In-Place Mutation Visible to Caller? Reassignment (x = new) Visible to Caller? Example Languages
Pass-by-Object-Reference (Call-by-Sharing) Passes a copy of the reference to the shared object Yes (for mutable objects like list, dict) No (only rebinds local parameter name) Python, Java (for objects), JavaScript, Ruby
Pass-by-Value Copies the entire value/struct onto the stack No (modifies local copy) No C, Go (default), Java (primitives)
Pass-by-Reference Passes an alias to the caller’s variable memory slot Yes Yes (overwrites caller’s variable directly) C++ (int&), C# (ref/out), PHP (&$x)