reference or pointer to some object?

Jeff Shannon jeff at ccvcorp.com
Tue Jan 11 16:29:36 EST 2005


Torsten Mohr wrote:

> Hi,
> 
> i'd like to pass a reference or a pointer to an object
> to a function.  The function should then change the
> object and the changes should be visible in the calling
> function.

There are two possible meanings of "change the object" in Python.  One 
of them will "just work" for your purposes, the other won't work at all.

Python can re-bind a name, or it can mutate an object.  Remember, 
names are just convenient labels that are attached to an object in 
memory.  You can easily move the label from one object to another, and 
the label isn't affected if the object it's attached to undergoes some 
sort of change.

Passing a parameter to a function just creates a new label on that 
object, which can only be seen within that function.  The object is 
the same, though.  You can't change what the caller's original label 
is bound to, but you *can* modify (mutate) the object in place.

 >>> def mutate(somedict):
... 	somedict['foo'] = 'bar'
... 	
 >>> def rebind(somedict):
... 	somedict = {'foo':'bar'}
... 	
 >>> d = {'a':1, 'b':2}
 >>> rebind(d)
 >>> d
{'a': 1, 'b': 2}
 >>> mutate(d)
 >>> d
{'a': 1, 'b': 2, 'foo': 'bar'}
 >>>

In mutate(), we take the object (which is d in the caller, and 
somedict in the function) and mutate it.  Since it's the same object, 
it doesn't matter where the mutation happened.  But in rebind(), we're 
moving the somedict label to a *new* dict object.  Now d and somedict 
no longer point to the same object, and when the function ends the 
object pointed to by somedict is garbage-collected, while the object 
pointed to by d has never changed.

So, to do what you want to do, you simply need to arrange things so 
that your parameter is an object that can be mutated in-place.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list