[Tutor] passing global variable as argument.

Bala subramanian bala.biophysics at gmail.com
Mon Jul 16 17:26:31 CEST 2012


Thank you wayne and steven. You suggestion to create a fresh array within
the function and assigning it to variable worked fine and the result was
exactly what i was looking for. In future i remember not to use global
variables as fn. parameters.

thanks once again for detailed explanation,
bala

On Mon, Jul 16, 2012 at 5:06 PM, Steven D'Aprano <steve at pearwood.info>wrote:

> 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
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>



-- 
C. Balasubramanian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120716/11628cf7/attachment-0001.html>


More information about the Tutor mailing list