Python global Keyword#

Learn about the global keyword, global variable and when to use global keyword.

Before reading this article, make sure you have got some basics of Python Global, Local and Nonlocal Variables.

What is global keyword?#

In Python, global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.

Rules of global Keyword#

The basic rules for global keyword in Python are:

  1. When we create a variable inside a function, it is local by default.

  2. When we define a variable outside of a function, it is global by default. You don’t have to use global keyword.

  3. We use global keyword to read and write a global variable inside a function.

  4. Use of global keyword outside a function has no effect.

Use of global Keyword#

# Example 1: Accessing global Variable From Inside a Function

a = 1 # global variable

def add():
    print(a)

add()
1

However, we may have some scenarios where we need to modify the global variable from inside a function.

# Example 2: Modifying Global Variable From Inside the Function

a = 1 # global variable
    
def add():
    a = a + 3 # increment a by 3 (modifying my global variable)
    print(a)

add()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-2-515941f58fe7> in <module>
      7     print(a)
      8 
----> 9 add()

<ipython-input-2-515941f58fe7> in add()
      4 
      5 def add():
----> 6     a = a + 3 # increment a by 3 (modifying my global variable)
      7     print(a)
      8 

UnboundLocalError: local variable 'a' referenced before assignment

This is because we can only access the global variable but cannot modify it from inside the function.

The solution for this is to use the global keyword.

# Example 2: Changing Global Variable From Inside a Function using global

a = 0 # global variable

def add():
    global a  # using global variable inside my function
    a = a + 3 # increment by 3
    print("Inside add():", a)

add()
print("In main:", a)
Inside add(): 3
In main: 3

Explanation:

In the above program, we define a as a global keyword inside the add() function.

Then, we increment the variable a by 1, i.e a = a + 3. After that, we call the add() function. Finally, we print the global variable a.

As we can see, change also occurred on the global variable outside the function, a = 3.

Let’s see another example where we don’t use global keyword to access the global variable in the function.

# Exercise 3: without `global` keyword.

global_var = 9   # Global variable

def fun1():
    print("Value in 1st function:", global_var)

def fun2():
    # Modify global variable
    # function will treat it as a local variable
    global_var = 999
    print("Value in 2nd function:", global_var)

def fun3():
    print("Value in 3rd function:", global_var)

fun1()
fun2()
fun3()
Value in 1st function: 9
Value in 2nd function: 999
Value in 3rd function: 9

Explanation:

As you can see, fun2() treated global_var as a new variable (local variable). To solve such issues or access/modify global variables inside a function, we use the global keyword.

# Exercise 3: use the `global` keyword.


x = 9   # Global variable

# defining 1st function
def fun1():
    print("Value in 1st function:", x)

# defining 2nd function
def fun2():
    # Modify global variable using global keyword
    global x
    x = 999
    print("Value in 2nd function:", x)

# defining 3rd function
def fun3():
    print("Value in 3rd function:", x)

fun1()
fun2()
fun3()
Value in 1st function: 9
Value in 2nd function: 999
Value in 3rd function: 999

Global Variables Across Python Modules#

In Python, we create a single module config.py to hold global variables and share information across Python modules within the same program.

Here is how we can share global variables across the python modules.

Example : Share a global Variable Across Python Modules#

Create a config.py file, to store global variables

>>> a = 0
>>> b = "empty"

Create a update.py file, to change global variables

>>> import config  # import config.py here

>>> config.a = 10  # change the value of 'a' from 0 to 10
>>> config.b = "alphabet"  # change the value of 'b' from "empty" to "alphabet"

Create a main1.py file, to test changes in value

>>> import config  # import config.py here
>>> import update  # import update.py here

>>> print(config.a)  # print the updated value of 'a'
>>> print(config.b)  # print the updated value of 'b'

When we run the main.py file, the output will be

10 alphabet

In the above, we have created three files: config.py, update.py, and main.py.

The module config.py stores global variables of a and b. In the update.py file, we import the config.py module and modify the values of a and b. Similarly, in the main.py file, we import both config.py and update.py module. Finally, we print and test the values of global variables whether they are changed or not.

Global in Nested Functions#

Here is how you can use a global variable in nested function.

# Example 1: Using a Global Variable in Nested Function

def fun():  # main function
    x = 30

    def day():  # nested fucntion
        global x
        x = 66
    
    print("Before calling bar function:", x)  # check indentation
    print("Calling bar function now")
    day()
    print("After calling bar function:", x)

fun()
print("x in main function:", x)
Before calling bar function: 30
Calling bar function now
After calling bar function: 30
x in main function: 66

Explanation:

In the above program, we declared a global variable inside the nested function day(). Inside fun() function, x has no effect of the global keyword.

Before and after calling day(), the variable x takes the value of local variable i.e x = 30. Outside of the fun() function, the variable x will take value defined in the day() function i.e x = 66. This is because we have used global keyword in x to create global variable inside the day() function (local scope).

If we make any changes inside the day() function, the changes appear outside the local scope, i.e. fun().