Newby Coder header banner

Python global, local and nonlocal

Python global Variable

In Python, a variable which is declared in global scope (outside functions) is known as a global variable

A global variable can be accessed inside or outside of functions

Python global keyword

The global keyword allows to modify a variable of the global scope

Info about scope & namespace

It can be used to declare a variable as global in a local context/namespace and make changes to the variable

Accessing global Variable From Inside a Function

Global variables can be read inside a function

x = 12
def printx():
    print(x)
printx()

Output when above program is run :

12 

There might be scenarios requiring to modify the global variable from inside a function

Modifying global variable from inside a Function

Consider following example, where modification to a global variable is attempted :

x = 12
def printx():
    x = x + 1
    print(x)
printx() 

When above code is run, Python shows error like:

UnboundLocalError: local variable 'x' referenced before assignment 

This is because the global variable can only be accessed inside a function but cannot be modified if not declared with global keyword

By using global keyword to declare a global variable, the variable can be modified inside the function

x = 12
def printx():
    global x
    x = x + 1
    print("value of x inside printx():", x)
print("value of x outside:", x)
printx()
print("value of x outside, after printx():", x)

Output

value off x outside: 12
value of x inside printx(): 13
value of x outside, after printx(): 13 

In the above example, x is declared as a global keyword inside printx() function, allowing it to be modified inside the function

Change also gets reflected outside of the printx() function

  • Similarly, a global variable can be manipulated in a nested function, by declaring it using global keyword

  • Global Variables Across Python Modules

    global variables can be shared across Python modules(or files) within a program

    Following example stores global variables in a file named constants.py and uses update.py to update them

    constants.py file is used to store global variables as

    count = 0
    b = ""
    c = False 

    An update.py file is created, to change global variables

    import constants
    
    constants.a = 10
    constants.b ="letters"
    
    def change_c():
        constants.c = True 

    A test.py file is created to test changes in value

    import constants
    import update
    
    print("a :", constants.a)
    print("b :", constants.b)
    print("c :", constants.c)
    update.change_c()
    print("c after constants.change_c() :", constants.c) 

    When test.py file is run, its output is as follows

    a : 10
    b : letters
    c : False
    c after constants.change_c() : True 

    In update.py file, the constants.py module is imported and the values of a and b are modified

    Similarly, in test.py file both config.py and update.py modules are imported and values of the global variables are tested

    change_c() method of update.py module is called to change value of c, which is then printed

    Local Variables

    A variable declared inside a function's body or in a local scope is known as local variable

    Creating a Local Variable

    Any variable declared or assigned inside a function is a local variable for that function

    def printy():
        y = "locally declared"
        print(y)
    
    foo() 

    Output

    locally declared
  • Since a local variable is only declared for a local scope, it cannot be accessed outside of the function it is defined in

  • Nonlocal Variables

    Nonlocal variables are used in nested function whose local scope is not defined

    This means, the variable can be neither in the local nor the global scope

    The nonlocal keyword is used to create nonlocal variable

    Example

    def printx():
        x = 12
        print("initial x:", x)
        def change():
            nonlocal x
            x = "twelve"
            print("x in nested fn change():", x)
        change()
        print("x in printx():", x)
    
    printx()

    Output

    initial x: 12
    x in nested fn change(): twelve
    x in printx(): twelve 

    In the above example, there is a nested function change() inside a function printx()

    nonlocal keyword to declare x as a nonlocal variable in printx() to refer to x declared in printx()

    Due to this, change to value of x done in change() method gets reflected in printx()