3 ms·
Referential Magic in Python
- viraptor 16y agoI think the article makes the matter more confusing than it should be. Actually many people make it more confusing. Just like with Java, Python passes only values. The value can be a reference to an object sometimes - that's pretty much it. Just like with Java, the call-by-whatever is sometimes misunderstood. It never behaves like call-by-reference. You can never do: def a(x): x = 42 and expect the value of `y` in your local scope to be changed after `a(y)`. I'd rather agree with the way Java defines it - call by value. Wikipedia: However, the term "call by sharing" is not in common use; the terminology is inconsistent across different sources. For example, in the Java community, they say that Java is pass-by-value, whereas in the Ruby community, they say that Ruby is pass-by-reference, even though the two languages exhibit the same semantics.
- bfw 16y agoUnless of course the value you pass is an object. In which case it will change in the scope you called the function from.
- driax 16y agoThe point is that you can't pass an object. The object lives on the heap and you always pass references around. Thats why when we pass in a list we can change the contents. The passed-in value is a copy of the reference to our list object. One of the trouble in python is if you really want to pass a reference to a true value such as an int. Usually I just wrap the int value in a list object because the syntax is fairly concise. Of course if you can you should avoid it, and in python 3 the most common occurrence is fixed with the nonlocal statement (which allows you to access the value of an outer scope, required with closures and non-reference values).
- viraptor 16y agoI'm not sure what you're saying here - care to give some example? The way I understand what you're saying - no - you don't pass "an object". In case of objects in Python, Java and others the value you pass then is a reference to that object. That reference cannot change in the calling scope.
- devinj 16y agoThe value can be a reference to an object sometimes - that's pretty much it. No, it's always a reference to an object. It's just that some objects are immutable and so the distinction is not so clear. Otherwise, all-around agreement. +1
- viraptor 16y agoI wrote "sometimes", because some implementation might JIT the code where a parameter is always an `int` and pass it in unboxed as the value itself (would be allowed due to no mutability). But yes - in "normal" python, it's always a reference.
- devinj 16y agoIn "Python", period. Implementation details don't affect statements about the language!
- deleted 16y ago[deleted]