Reputation: 15803
I wrote this code:
sample_array = ones ([N, 3], dtype = float)
def get_training_set ():
r = rand (N, 2) * 2 - 1
sample_array[:,[0,1]] = r
return sample_array
I declared the sampling array outside, in order not to allocate it all the time, just to modify it -- the last coordinate is always 1.
Initially I expected that I have to insert a statement "global sample_array" in function, because I modify it, and consequently the evaluator should know that it's a global var.
But, to my surprise, it works well without "global". Why does it work ? Where/what is the definition of evaluation in this case ?
Upvotes: 1
Views: 3115
Reputation: 108
I think it's because sample_array is not declared inside the function, but just write. Python cannot find sample_array in side function namespace, it will find the outer namespace. E.g.
a = []
def test1():
a.append(1) # will use the outer one
def test2():
a = []
a.append(1) # will use the inner one
Global, sometimes, for declare a global variable:
def declare_global():
global b # this should be global after 'declare_global()' is called
b = 1
print b # raise NameError: name 'b' is not defined
declare_global()
print b # will output '1'
Upvotes: 1
Reputation: 310097
global
is necessary if you are changing the reference to an object (e.g. with an assignment). It is not necessary if you are just mutating the object (e.g. with slice assignment like what you've done above).
The exact documentation is here.
The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals.
So, with the global statement, you're telling python that the variable lives in the global context. If you assign to it, then you change the value in the global context.
If you don't use the global statement, python decides whether the variable is local or nonlocal. (In fact, python3.x added a nonlocal
keyword). The variable is nonlocal if it appears first on the right side of an assignment, or if you do item assignment (x[...] = ...
) or attribute assignment (x.whatever = ...
). If the variable is local, that means that it was created in the function (or is an input argument). You can reassign directly to a local identifier and there's no problem. If the variable is non-local, you can mutate it, but you can't re-assign it because then python is unable to determine whether the variable is local or non-local.
Upvotes: 2