Pass by reference or by value?

Thomas Jollans thomas at jollans.com
Thu Aug 16 19:20:02 EDT 2007


On Thursday 16 August 2007, Robert Dailey wrote:
> Hi,
>
> I previously created a topic named "Pass by reference or by value" where I
> inquired on how python's function parameters work. I received a lot of nice
> responses, however I'm still confused on the topic. Note that I come from a
> C++ background to Python, so any comparisons to C++ would be very helpful.

Very short answer:

Think of normal objects as always-pointers. There are no references. param = 5 
sets the local variable "param" (be that of imaginary type int* or int, I 
don't care) to whatever 5 is. This does not call an operator=, this plain 
overwrites the variable.

If you want to change arguments in that way, you can use a list as an ugly 
hack:

def foo(param):
	param[0] = 5
	print param[0]

a = [4]

foo(a)

yeah, I said ugly. That hack makes sure that a method of the passed object is 
called instead of of the local namespace dict. (please note that I'm throwing 
around abstract concepts without caring about an implementation).

-- 
      Regards,                       Thomas Jollans
GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu
Hacker key <http://hackerkey.com/>:
v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 196 bytes
Desc: This is a digitally signed message part.
URL: <http://mail.python.org/pipermail/python-list/attachments/20070817/31d70695/attachment.sig>


More information about the Python-list mailing list