Saturday, August 10, 2013

You know what really grinds my gears? (In Python)

I can never correctly remember when things are passed as references or copied as local variables inside functions.

Take these two, innocuously looking functions. Because both do the same thing (namely set the contents of a vector, P, to [1, 1]) I call them 1 and a, respectively, since one is not better than the other.

def implementation_1(P):

P = [1, 1]

def implementation_a(P):

P[0] = 1 P[1] = 1

What you would expect is one of the following two options

Both functions change P to [1, 1] (permanently).

Both functions take a local copy of P and change it to [1, 1], and after the function returns, the local [1, 1] array is forgotten.

A simple test is to do this:

P = [0, 0]print P

implementation_1(P)print P

implementation_a(P)print P

which prints:

[0, 0][0, 0][1, 1]

So clearly implementation_a() is different from implementation_1(), although they seemingly do the same.