In Python what is a global statement?
Every "variable" in python is limited to a certain scope. The scope of a python "file" is the module-scope. Consider the following:
#file test.py
myvariable = 5 # myvariable has module-level scope
def func():
x = 3 # x has "local" or function level scope.
Objects with local scope die as soon as the function exits and can never be retrieved (unless you return
them), but within a function, you can access variables in the module level scope (or any containing scope):
myvariable = 5
def func():
print(myvariable) # prints 5
def func2():
x = 3
def func3():
print(x) # will print 3 because it picks it up from `func2`'s scope
func3()
However, you can't use assignment on that reference and expect that it will be propagated to an outer scope:
myvariable = 5
def func():
myvariable = 6 # creates a new "local" variable.
# Doesn't affect the global version
print(myvariable) # prints 6
func()
print(myvariable) # prints 5
Now, we're finally to global
. The global
keyword is the way that you tell python that a particular variable in your function is defined at the global (module-level) scope.
myvariable = 5
def func():
global myvariable
myvariable = 6 # changes `myvariable` at the global scope
print(myvariable) # prints 6
func()
print(myvariable) # prints 6 now because we were able
# to modify the reference in the function
In other words, you can change the value of myvariable
in the module-scope from within func
if you use the global
keyword.
As an aside, scopes can be nested arbitrarily deeply:
def func1():
x = 3
def func2():
print("x=",x,"func2")
y = 4
def func3():
nonlocal x # try it with nonlocal commented out as well. See the difference.
print("x=",x,"func3")
print("y=",y,"func3")
z = 5
print("z=",z,"func3")
x = 10
func3()
func2()
print("x=",x,"func1")
func1()
Now in this case, none of the variables are declared at the global scope, and in python2, there is no (easy/clean) way to change the value of x
in the scope of func1
from within func3
. That's why the nonlocal
keyword was introduced in python3.x . nonlocal
is an extension of global
that allows you to modify a variable that you picked up from another scope in whatever scope it was pulled from.
When is the global statement necessary?
By default, an assignment to a name always operates on a local variable, creating a new one if it is not currently defined.
The global
statement makes the name refer to a variable in the global scope, permitting you to assign to a global name without creating a new local variable.
(The nonlocal
statement does something similar, except it makes the name refer to a variable defined in the closest enclosing scope, which is not necessarily the global scope.)
In your first example, you are not assigning to a name; you are performing attribute lookup on a free variable, which resolves to the global variable of the same name.
In your second example, you try to create a new local variable. Since scope is determined at compile time, a = a + [1]
will fail, because the a
on the right-hand side will still refer to the as-of-yet undefined local variable a
. With global
, the assignment does not create a local variable, so the right-hand side is an expression involving the global variable, and the result is assigned to the global name as well.
Global array -- no need for global statement
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.
global statement isn't working, and I don't understand why
Your function sets a variable named value
to zero, leaving g untouched. If you want to change, g
, this code would do it:
def zerofunc(value):
global g
g = 0
g = 15
zerofunc(g)
print(g)
That being said, there doesn't appear to be a good reason to make g
global; globals are generally discouraged.
Global variables and global statement from other modules
Each module has its own global name scope. By importing everything via *
from another module, you create copies (additional references to the values) of the globals of the other module into your own module.
Use qualified names in order to prevent this from happening:
import module_1
module_1.set_g_up()
print module_1.g
There is no way to access the same variable by calling it g
if you in fact mean the variable module_1.g
. All you can make happen is that both variables contain the same value (makes only sense for lists, objects and other mutables).
Related Topics
Process to Convert Simple Python Script into Windows Executable
Programmatically Searching Google in Python Using Custom Search
How to Specify an Authenticated Proxy for a Python Http Connection
Replacing Text in a File with Python
How to Make Python Scripts Executable on Windows
Heapq with Custom Compare Predicate
How to Set Env Variable in Jupyter Notebook
Get Raw Post Body in Python Flask Regardless of Content-Type Header
Python: Http Post a Large File with Streaming
Why Don't Methods Have Reference Equality
List() Uses Slightly More Memory Than List Comprehension
Getting the Docstring from a Function
Creating Dynamically Named Variables from User Input
How to Extract Top-Level Domain Name (Tld) from Url