[Tutor] passing global variable as argument.

Steven D'Aprano steve at pearwood.info
Mon Jul 16 17:06:15 CEST 2012


Bala subramanian wrote:
> Friends,
> I want to define a function that can populate an array by taking its name
> (which is defined globally). I defined two empty arrays as follows and a
> function that can populate the array.

In general it is tricky to resize and populate numpy arrays in place. It is 
usually better to just create a fresh array and reassign it. Something like 
this should probably work:

def ref(length):
     arr = np.zeros((length, 3), dtype='float32')
     for i in range(length):
         for j in range(3):
             arr[i, j] = resid[Index[i]].cent()[j]
     return arr


ref_f1 = ref(3)
ref_f2 = ref(5)


should work for you. (I can't test it because you don't say what resid and 
Index are.)



To explain why your earlier code does not work the way you expect, read on:


> REF_F1=np.array([])
> REF_F2=np.array([])
> 
> # populating the given array
> def ref(ln,REF_F1):

So far this is good -- your function takes an argument called "REF_F1", which 
can be any array you like. It's just a local name.

The function sees REF_F1 is a local variable.


>     global REF_F1

But this is no good, because now you declare the name REF_F1 to be global 
instead of local. So now the function sees REF_F1 as a global variable, and 
everything that you do to it, occurs to the global called REF_F1.

By the way, this bug is no longer permitted in the latest version of Python. 
Using Python 3.2:

py> x = 23
py> def func(x):
...     global x
...     print("x =", x)
...
   File "<stdin>", line 1
SyntaxError: name 'x' is parameter and global


In general, if you feel the need to use "global", 90% of the time you are 
doing something wrong and will have problems. You should avoid using global 
unless absolutely necessary.



-- 
Steven


More information about the Tutor mailing list