Hacker News new | ask | show | jobs
by Joeboy 1295 days ago
My understanding of what's going on with python is it passes by reference (hence what your code does), but if the data type is immutable any modification results in a new instance being created in the scope of the function, and the object passed in is not modified. Which mostly looks like pass-by-value behaviour.

I guess my understanding could be technically wrong in some way, but it seems to reflect what happens.

1 comments

The issue is that Python passes references by value, so you cannot overwrite what the arguments of a function reference from the perspective of the caller. However, if you pass something like a dictionary or a class the function gets a copy of the reference and can use it to update the members of what was passed. Java operates on the same principle, although there may be some edge cases I'm not aware of where the two differ.
Perhaps I'm being simple minded, but the id of the passed object within the function is the same as the id of the object outside the function, no? My mental model is that an object's id in python is basically an address / pointer. So, how come it's the same inside the function as outside, if it's not pass by reference?
You're correct that the id is the same inside and outside the function, but when you modify the passed in argument the id changes because you're setting the value of the parameter, not what it's referencing. In C it'd be like changing the value of a pointer in a function instead of the value referenced by a pointer in a function.

Here's an example to include the id differences and the fact that a does not take on the value of d:

  >>> def f(d):
  ...     print(f"id: '{id(d)}'")
  ...     d = {'foo': 'bar'}
  ...     print(f"id: '{id(d)}'")
  >>> a = {}
  >>> a
  {}
  >>> id(a)
  140362610196224
  >>> f(a)
  id: '140362610196224'
  id: '140362610196160'
  >>> a
  {}
  >>> id(a)
  140362610196224

But, as I've posted elsewhere in this thread, this example will change the contents of 'd' since d itself is not being set, its contents are:

  >>> def f(d):
  ...     d['foo'] 'bar'}
  ... 
  >>> a = {}
  >>> f(a)
  >>> a
  {'foo': 'bar'}
Until the second line of your function (in the first example), it's pass by reference, no? It stops behaving like pass-by-reference because you then reuse the name 'd' to create a new object, which has a different id and lives at a different address.

At least, this seems like a coherent mental model of what's happening, to me.

I'm not re-using the name 'd', I'm assigning to the already-existing parameter d. Which if d was indeed a reference would result in the variable passed to the function being changed.

In explaining this I decided to check the Python docs and learned a new piece of terminology "pass by assignment", which is how Python explains its variable passing scheme: https://docs.python.org/3/faq/programming.html#how-do-i-writ...