Hacker News new | ask | show | jobs
by rockemsockem 1295 days ago
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'}
1 comments

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...