Please help with MemoryError
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Fri Feb 12 12:14:57 EST 2010
On Fri, 12 Feb 2010 06:45:31 -0800, Jeremy wrote:
> You also confirmed what I thought was true that all variables are passed
> "by reference" so I don't need to worry about the data being copied
> (unless I do that explicitly).
No, but yes.
No, variables are not passed by reference, but yes, you don't have to
worry about them being copied.
You have probably been mislead into thinking that there are only two
calling conventions possible, "pass by value" and "pass by reference".
That is incorrect. There are many different calling conventions, and
different groups use the same names to mean radically different things.
If a language passes variables by reference, you can write a "swap"
function like this:
def swap(a, b):
a, b = b, a
x = 1
y = 2
swap(x, y)
assert (x == 2) and (y==1)
But this does not work in Python, and cannot work without trickery. So
Python absolutely is not "pass by reference".
On the other hand, if a variable is passed by value, then a copy is made
and you can do this:
def append1(alist):
alist.append(1) # modify the copy
return alist
x = []
newlist = append1(x)
assert x == [] # The old value still exists.
But this also doesn't work in Python! So Python isn't "pass by value"
either.
What Python does is called "pass by sharing", or sometimes "pass by
object reference". It is exactly the same as what (e.g.) Ruby and Java
do, except that confusingly the Ruby people call it "pass by reference"
and the Java people call it "pass by value", thus guaranteeing the
maximum amount of confusion possible.
More here:
http://effbot.org/zone/call-by-object.htm
http://en.wikipedia.org/wiki/Evaluation_strategy
--
Steven
More information about the Python-list
mailing list