[Tutor] passing global variable as argument.

Dave Angel d at davea.name
Mon Jul 16 13:31:37 CEST 2012


On 07/16/2012 07:00 AM, 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.
>
> REF_F1=np.array([])
> REF_F2=np.array([])
>
> # populating the given array
> def ref(ln,REF_F1):
>     global REF_F1
>     REF_F1=np.zeros((ln,3),dtype='float32')
>     for i in range(ln):
>         for j in range(3):
>            REF_F1x[i,j]=resid[Index[i]].cent()[j]
>
> 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.
>
> Thanks,
> Bala
>
>
>

When you use a non-standard library, you really ought to mention what it
is.  I'm assuming np refers to numpy, which i'm not familiar with.  So I
won't address any particular quirks of that library.

When you use the global statement in a function, you are saying you want
a particular global value, so the argument detail is irrelevant.  Seems
to me it should have been a compile error.

Nix the global statement if you really want to pass it as an argument. 
And for readability, call the formal parameter something else, and do
not capitalize it.  it's not read-only; you're intending to change it.

Since I don't know numpy, I'll have to use a built-in type for example. 
I choose list.

(untested)
myglobal1 = [3,4]
myglobal2 = [5,6,7]

def  myfunc(ln, target):
    while target: target.pop()
    for i in xrange ln:
             target.append(3*i)
    for j in xrange(ln):
             target[j] += 5

myfunc(10, myglobal1)
myfunc(5, myglobal2)

A key point is I do not bind my local variable target to a new object. 
If I do, I'll have no effect on the global object.  So I cannot use the
following line:
     target = []

I also notice you use 'ref' several places.  Perhaps you're under the
mistaken belief that Python does references.

-- 

DaveA



More information about the Tutor mailing list