Global Variables
Variables that are created outside of a function [as in all of the examples above] are known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
Example
Create a variable outside of a function, and use it inside the function
x = "awesome"
def myfunc[]:
print["Python is " + x]
myfunc[]
Try it Yourself »
If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.
Example
Create a variable inside a function, with the same name as the global variable
x = "awesome"
def myfunc[]:
x = "fantastic"
print["Python is " + x]
myfunc[]
print["Python is " + x]
Try it Yourself »
The global Keyword
Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.
To create a global variable inside a function, you can use
the global
keyword.
Example
If you use the global
keyword, the variable belongs to the global scope:
def myfunc[]:
global x
x = "fantastic"
myfunc[]
print["Python is " + x]
Try it Yourself »
Also, use the global
keyword if you want to change a global variable inside a function.
Example
To change the value of a global variable inside a function, refer to the variable by using the global
keyword:
x = "awesome"
def myfunc[]:
global x
x = "fantastic"
myfunc[]
print["Python is " + x]
Try it Yourself »
Within a Python scope, any assignment to a variable not already declared within that scope creates a new local variable unless that variable is declared earlier in the function as referring to a globally scoped variable with the keyword global
.
Let's look at a modified version of your pseudocode to see what happens:
# Here, we're creating a variable 'x', in the __main__ scope.
x = 'None!'
def func_A[]:
# The below declaration lets the function know that we
# mean the global 'x' when we refer to that variable, not
# any local one
global x
x = 'A'
return x
def func_B[]:
# Here, we are somewhat mislead. We're actually involving two different
# variables named 'x'. One is local to func_B, the other is global.
# By calling func_A[], we do two things: we're reassigning the value
# of the GLOBAL x as part of func_A, and then taking that same value
# since it's returned by func_A, and assigning it to a LOCAL variable
# named 'x'.
x = func_A[] # look at this as: x_local = func_A[]
# Here, we're assigning the value of 'B' to the LOCAL x.
x = 'B' # look at this as: x_local = 'B'
return x # look at this as: return x_local
In fact, you could rewrite all of func_B
with the variable named x_local
and it would work identically.
The order
matters only as far as the order in which your functions do operations that change the value of the global x. Thus in our example, order doesn't matter, since func_B
calls func_A
. In this example, order does matter:
def a[]:
global foo
foo = 'A'
def b[]:
global foo
foo = 'B'
b[]
a[]
print foo
# prints 'A' because a[] was the last function to modify 'foo'.
Note that global
is only required to modify global objects. You can still access them from within a function without declaring global
. Thus, we have:
x = 5
def access_only[]:
return x
# This returns whatever the global value of 'x' is
def modify[]:
global x
x = 'modified'
return x
# This function makes the global 'x' equal to 'modified', and then returns that value
def create_locally[]:
x = 'local!'
return x
# This function creates a new local variable named 'x', and sets it as 'local',
# and returns that. The global 'x' is untouched.
Note the difference between create_locally
and access_only
-- access_only
is accessing the global x despite not
calling global
, and even though create_locally
doesn't use global
either, it creates a local copy since it's assigning a value.
The confusion here is why you shouldn't use global variables.
Global & local variables with same name
Checkout this example,
Advertisements
total = 100 def func1[]: total = 15 print['Total = ', total] func1[] print['Total = ', total]
Output:
Total = 100 Total = 100
Here 'total' is a global variable and func[] function has a local variable with same name. By default a function gives preference to
local variable over global variable if both are of same name. Therefore in above code when we modified 'total' variable inside the
function then it was not reflected outside the function. Because inside function func[] total variable is treated as local variable.
But what if want to access global variable inside a function that has local variable with same name ?
Use of “global†keyword to modify global variable inside a function
If your function has a local variable with same name as global variable and you want to modify the global variable inside function then use 'global' keyword before the variable name at start of function i.e.
global total
It will make the function to refer global variable total whenever accessed. Checkout this example,
total = 100 def func[]: # refer to global variable 'total' inside function global total if total > 10: total = 15 print['Total = ', total] func[] print['Total = ', total]
Output:
Total = 100 Total = 15
As you can see modification done to global variable total is now visible outside the function too.
When we use global keyword with a variable inside the function then the local variable will be hidden. But what if we want to keep bot the local & global variable with same and modify both in the function ? Let's see how to do that,
Using globals[] to access global variables inside the function
As 'global' keywords hide the local variable with same name, so to access both the local & global variable inside a function there is an another way i.e. global[] function.
globals[] returns a dictionary of elements in current module and we can use it to access / modify the global variable without using 'global' keyword i,e.
total = 100 def func3[]: listOfGlobals = globals[] listOfGlobals['total'] = 15 total = 22 print['Local Total = ', total] print['Total = ', total] func3[] print['Total = ', total]
Output:
Total = 15 Local Total = 22 Total = 11
As you can see that we have local variable and global variable with same name i.e. total and we modified both inside the function. By using dictionary returned by globals[] to refer global variable instead of keyword 'global'. It will not hide local variable inside the function.
Handling UnboundLocalError Error
If we try to access a global variable with 'global' keyword or globals[] inside a function i.e.
total = 22 def func2[]: if total > 10: total = 15
It will throw an error like this,
UnboundLocalError: local variable 'total' referenced before assignment
To prevent this error we either need to use 'global' keyword or global[] function i.e.
total = 22 def func2[]: global total if total > 10: total = 15
The Complete example of global variable and globals[] in Python
# Global variable total = 100 def test[]: # Local variable marks = 19 print['Marks = ', marks] print['Total = ', total] def func1[]: total = 15 def func[]: # refer to global variable 'total' inside function global total if total > 10: total = 15 def func2[]: global total if total > 10: total = 15 def func3[]: listOfGlobals = globals[] listOfGlobals['total'] = 11 total = 22 print['Local Total = ', total] def main[]: print['Total = ', total] func1[] print['Total = ', total] func[] print['Total = ', total] func2[] print['Total = ', total] func3[] print['Total = ', total] if __name__ == '__main__': main[]
Output:
Total = 100 Total = 100 Total = 15 Total = 15 Local Total = 22 Total = 11