The Python global Keyword

Introduction

The Python global keyword is used to access and modify global variables from within a function’s local scope. It tells Python that a variable assigned in a function should refer to a global variable. Otherwise, Python will create a local variable of the same name.

Using the Python global Keyword

To use the global keyword, simply write global followed by the name of the variable in the global scope:

global global_variable

The above statement will make sure the variable named global_variable will be treated as a global variable.

Example:

global_var = 10 

def modify_global():
    global global_var 
    global_var = 20 

modify_global()
print("Global variable:", global_var)  

Output:

Global variable: 20

In the example above, the global keyword inside the modify_global() function (line 4) indicates that global_var refers to the global variable first declared externally (line 1). When the function modifies global_var by setting it to 20 (line 5), it is the global variable that changes. Consequently, when global_var is printed the function (line 8), the output is 20.

What Happens Without global

If you don’t use the global keyword and attempt to assign a value to a global variable within the local scope of a function, Python will create a local variable instead.

Example:

global_var = 10 

def modify_global(): 
    global_var = 20  # This is a local variable here!

modify_global()
print("Global variable:", global_var) 

Output:

Global variable: 10

The only difference between this and the previous example’s code is the removal of the global global_var statement in the modify_global() function. Now, when global_var is assigned a value inside modify_global() (line 4), it is actually a local variable by that name that gets the value, not the global global_var. Therefore, when global_var is printed (line 7) it is unchanged and still has the value of 10.

global Creates a Global Variable If One Does Not Exist

The global variable referenced by a global keyword does not need to have been created in the global scope beforehand. If it does not exist, the global statement creates it.

Example:

def modify_global():
    global global_var 
    global_var = 20 

modify_global()
print("Global variable:", global_var)  

Output:

Global variable: 20

In the example above, when the function modify_global() assigns 20 to global_var (line 3), it’s the first time global_var is used. However, the global global_var statement (line 2) creates it.

Drawbacks of Using global

If you are using the Python global keyword, it means that you need to modify a global variable inside a function. While this can be convenient, it’s generally considered a best practice to minimize the use of global variables within functions. Here are a few reasons why:

  1. Code Readability: When functions use global variables, they can be challenging to understand and debug. To debug, you might have to trace back to find where a global variable is defined and how it’s being modified.
  2. Code Maintainability: Global variables make code less modular and more tightly coupled. This can lead to issues when making changes or refactoring code, since modifications to a global variable in one function could unintentionally affect other parts of the program.
  3. Testing: Unit testing becomes more complex when functions depend on global state. Mocking or stubbing global variables for testing purposes can be cumbersome.

Alternatives to Using Global Variables Within Functions

Because of the drawbacks above, it is advisable to refactor code to reduce reliance on global state where possible. If you need to access a global variable in a function, consider passing its value as an argument, and if you need to modify a global variable, have a function return the modified value and assign it in the global scope.

Let’s illustrate this with two examples. The first uses the global variable within the function, and the second does not.

Example:

global_var = 5

def square_global():
    global global_var
    global_var = global_var**2
    
square_global()
print("Squared variable:", global_var)

Output:

Squared variable: 25

In the example above, the square_global() function (line 3) accesses and modifies the global variable global_var (line 5) in order to square it. It’s then squared (line 7) and printed (line 8) at the end of the script.

The next example rewrites the code so that the function does not use the global variable.

Example:

global_var = 5

def square_number(num):
    return num**2
    
global_var = square_number(global_var)
print("Squared variable:", global_var)

Output:

Squared variable: 25

In the second example above, the function is square_number() (line 3). It has the parameter num and returns its square (line 4). The function is not only more decoupled because it does not use an external variable, but also as an extra “bonus”, its more generic since it’s capable of squaring any number, not just global_var. The global variable is modified by assignment to the value the function returns (line 6). Since it’s not buried inside a function, as in the previous example, this assignment statement makes it much more obvious that global_var is modified at this point.

Summary & Reference for the Python global Keyword

The Python global keyword lets you modify and access global variables within local function scopes. Without it, functions attempting to assign a value to a global variable within a function, crate a local variable with the same name instead, potentially leading to unintended behavior.


To use the global keyword, simply write global followed by the name of the variable in the global scope.

global global_var

If the global keyword is omitted within a function, Python will create a new local variable with the same name as the global variable.

global_var = 10

def modify_global(): 
    global_var = 20  # This is a local variable here!
    
modify_global()
print(global_var)  # --> 10

The global keyword creates a global variable if it doesn’t already exist.

def modify_global():
    global global_var
    global_var = 20
 
modify_global()   
print(global_var)  # --> 20

Use of global variables within local scopes can lead to code readability and maintainability issues, making debugging and testing more challenging. It’s advisable to minimize reliance on global variables within functions whenever possible.