Please help with MemoryError

Antoine Pitrou solipsis at pitrou.net
Fri Feb 12 23:27:32 CET 2010


Le Fri, 12 Feb 2010 17:10:01 -0500, Steve Holden a écrit :
> 
> As has already been pointed out, if Python used call by reference then
> the following code would run without raising an AssertionError:
> 
> def exchange(a, b):
>     a, b = b, a
> 
> x = 1
> y = 2
> exchange(x, y)
> assert (x == 2 and y == 1)
> 
> Since function-local assignment always takes place in the function
> call's local namespace

I don't think this is related to a difference in parameter passing style.

It's just that assignment ("=") means a different thing in Python than in 
non-object languages (or fake-object languages such as C++ or PHP): it 
rebinds instead of mutating in-place. If it mutated, you wouldn't have 
the AssertionError.

If you mutate in-place:

>>> def exchange(a, b):
...     t = a[:]
...     a[:] = b
...     b[:] = t
... 
>>> x, y = [1], [2]
>>> exchange(x, y)
>>> x, y
([2], [1])

Regards

Antoine.




More information about the Python-list mailing list