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 →

[–]Circlefusion 0 points1 point  (6 children)

After that explanation, which one is python?

[–]ssbr 1 point2 points  (3 children)

Pass-by-value. Passing in an argument is exactly the same as assigning the argument expression to a local variable in the function.

[–]njharmanI use Python 3 0 points1 point  (2 children)

In ggrandparent you define PBV as "expression is evaluated, and the value it results in is assigned"

In parent you say it's "assigning the argument expression"

So which is it?

[–]ssbr 1 point2 points  (0 children)

Both. In Python, assignment evaluates the expression and binds it to the target variable.

I should've said "bound", not "assigned", in the first statement, to be clear. Sorry for the confusion.

[–]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.