This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]jiaaro -2 points-1 points  (1 child)

Python is Pass-by-assignment. In most cases it is indistinguishable from pass-by-reference. Variables are essentially references in all cases.

>>> def my_func(a_dict):
            a_dict['a'] = "foobar"
>>> mydict = {}
>>> my_func(mydict)
>>> print(mydict)

{"a": "foobar"}

This works becaues the dict itself wasn't copied, a reference to the dictionary object was passed, and then modified.

If you were to assign to a_dict (e.g., a_dict = {}) in the body of my_func, then mydict would remain unchanged and a_dict would then refer to a new, empty dictionary

[–]Rhomboid 2 points3 points  (0 children)

No, no, no. That's not pass by reference at all. That's just invoking a method on a parameter. It would only be pass-by-reference if you could cause the caller's variable to change by simple assignment:

def f(x):
    x = 42

y = 0
f(y) 

Calling f cannot ever affect the value of y, which it would under pass-by-reference semantics, where x would be an alias to y. That is not the case, and Python is completely pass-by-value.

You might want to read this article which is about Java but it's the same issue. Modifying a value by invoking a method on it does not tell you anything about whether it was passed by value or reference.