Python global Keyword

Creates or Updates a global variable from a nonglobal scope

Usage

The global keyword is used to create or update a global variable from a nonglobal scope (such as inside a function or a class).

Syntax

global var1,var2,

Python global keyword parameters
ParameterConditionDescription
var1,var2,…RequiredList of identifiers you want to declare global

Modifying Globals Inside a Function

A variable declared outside all functions has a GLOBAL SCOPE.

It is accessible throughout the file, and also inside any file which imports that file.

Example: Get the value of the global variable x

x = 42          # global scope x

def myfunc():
    print(x)    # x is 42 inside def

myfunc()
print(x)        # x is 42 outside def

Although you can access global variables inside or outside of a function, you cannot modify it inside a function.

Here’s an example that tries to reassign a global variable inside a function.

Example:

x = 42          # global scope x
def myfunc():
    x = 0
    print(x)    # x is 0

myfunc()
print(x)        # x is still 42

Here, the value of global variable x didn’t change. Because Python created a new local variable named x; which disappears when the function ends, and has no effect on the global variable.

To access the global variable rather than the local one, you need to explicitly declare x global, using the global keyword.

Example: Reassign a global variable inside a function

x = 42          # global scope x
def myfunc():
    global x
    x = 0
    print(x)    # global x is now 0

myfunc()
print(x)        # x is 0

The x inside the function now refers to the x outside the function, so changing x inside the function changes the x outside it.

Here’s another example that tries to update a global variable inside a function.

Example:

x = 42          # global scope x

def myfunc():
    x = x + 1   # raises UnboundLocalError
    print(x)

myfunc()
print(x)

Here, Python assumes that x is a local variable, which means that you are reading it before defining it.

The solution, again, is to declare x global.

Example: Modify a global variable inside a function

x = 42          # global scope x

def myfunc():
    global x
    x = x + 1   # global x is now 43
    print(x)

myfunc()
print(x)        # x is 43

There’s another way to update a global variable from a no-global scope – use globals() function.

Create Globals Inside a Function

When you declare a variable global, it is added to global scope, if not already present.

Example: Declare x global inside a function and access it outside the function

def myfunc():
    global x    # x should now be global
    x = 42

myfunc()
print(x)        # x is 42