[Tutor] passing global variable as argument.

Wayne Werner wayne at waynewerner.com
Mon Jul 16 13:37:05 CEST 2012


On Mon, 16 Jul 2012, Bala subramanian wrote:

> Friends,
> I want to define a function that can populate an array by taking its name
> (which is defined globally).

Are you sure this is what you really want to do? I've noticed that many times
that I want to do something, but only because I don't understand how to do it a
better way.

> I defined two empty arrays as follows and a
> function that can populate the array.
>
> REF_F1=np.array([])
> REF_F2=np.array([])
>
> # populating the given array
> def ref(ln,REF_F1):
>    global REF_F1

My command of the global syntax is a little weak, but I'm going to say what is
probably happening with this line is that you are telling python you now want
to refer to the REF_F1 that lives in the global namespace, not the one that was
passed in to your function.

>    REF_F1=np.zeros((ln,3),dtype='float32')

This line here tells me that what I mentioned first is correct. You don't care
*what* the array is before hand, because you're actually zeroing the array.
Read the conclusion below.

>    for i in range(ln):
>        for j in range(3):
>           REF_F1x[i,j]=resid[Index[i]].cent()[j]

I'm not sure what `resid` or `Index` are. Also, REF_F1x wasn't defined anywhere
so you're probably getting a name error here. When sending code, especially
misbehaving code, the best thing to do is provide a SMALL, but complete
program that can be run on its own, as long as one has the dependencies.

>
> ref(ln, REF_F2)
>
> In this case, when i pass REF_F2 as argument, the fn. always populates
> array REF_F1. I also tried something like the following
> *def ref(ln,x=REF_F1)* and then calling as *ref(ln,x=REF_F2)*. The result
> is the same. Could someone please give me hint on how pass global variables
> as arguments.

First off, the whole point of global variables are so that you don't have to
pass them as arguments. This is fine, and there are occasions where you
legitimately want to have a global variable - but this isn't one of them. When
you use globals improperly, they cause maintenance nightmares by making it
really hard to figure out what's going on in your code. At least Python
requires you to explicitly state that you care about some global value with the
global keyword.

But in this case it looks like you don't actually care about the original array
- you're completely replacing the values based on whatever the value of `ln`
   is. So instead you could do something like

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

And then you would call it like this:

     REF_F2 = ref(ln)

HTH,
Wayne


More information about the Tutor mailing list