Wednesday, June 15, 2022

Local, Nonlocal And Global Variables in Python

In this post we’ll learn about global variables, local variables and nonlocal variables in Python, what is the scope of these variables and usage examples.


Global variable in Python

Variables that are declared outside a function are known as global variables in Python. These variables have a greater scope and are available to all the functions that are defined after the declaration of global variable.

Python global variable example

#global variable
x = 10
def function1():
  y = 7
  print("x in function1=", x)
  print("y in function1=", y)

def function2():
  print("x in function2=", x)

function1()
function2()
#scope here too
print('x=', x)

Output

x in function1= 10
y in function1= 7
x in function2= 10
x= 10

In the example variable x is declared outside any function so it’s scope is global. This global variable x can be accessed inside the functions as well as outside the functions (as done in last print statement).

Local variable in Python

When a variable is declared inside a function then it is a local variable. A local variable’s scope is limited with in the function where it is created which means it is available with in the function where it is declared not outside that function.

If we modify the above example a bit and bring variable x with in the function1() then you will get an error as x won’t be visible in function2() or outside any function.

def function1():
  x = 10
  y = 7
  print("x in function1=", x)
  print("y in function1=", y)

def function2():
  print("x in function2=", x)

function1()
function2()
# no scope here
print('x=', x)

output

x in function1= 10
y in function1= 7
 File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 12, in <module>
    function2()
  File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 9, in function2
    print("x in function2=", x)
NameError: name 'x' is not defined

global keyword in Python

As we have learned till now a variable declared outside any function has a global scope where as a variable declared inside any function has a local scope. If you declare a variable inside a function having the same name as the global variable then with in the scope of the method local variable overshadows the global variable.

x = 10
def function():
  #local var
  x = 12
  print("x in function=", x)

function()
# Outside function
print('x=', x)

Output

x in function= 12
x= 10

As you can see here inside function() x has the value 12 even if there is a global variable x with value 10.

Now consider the scenario where you want to modify the global variable itself inside a function. You will get an error ‘local variable 'x' referenced before assignment’ because Python looks for x declaration with in the function which is not found thus the error.

x = 10
def function():
  x = x + 1
  print("x in function=", x)

function()
# Outside function
print('x=', x)

Output

  File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 6, in <module>
    function()
  File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 3, in function
    x = x + 1
UnboundLocalError: local variable 'x' referenced before assignment

Python global keyword example

In such scenario, where you want to use the global variable inside a function, you can use global keyword with the variable in the start of the function body.

x = 10
def function():
  # to access global variable
  global x
  x = x + 1
  print("x in function=", x)

function()
# Outside function
print('x=', x)

Output

x in function= 11
x= 11

Python global variable in class example

Suppose you want to have a global variable which has to retain its updated value for all the class instances so that any new object gets the updated value. Since, the global statement is a declaration which holds for the entire current code block so using global keyword you can do that as follows.

class MyClass():
  global count
  count = 10

  def mymethod(self):
    global count
    count += 1
    print("count in mymethod=", count)

obj1 = MyClass()
obj1.mymethod()
print('count=', count)
obj2 = MyClass()
obj2.mymethod()
print('count=', count)

Output

count in mymethod= 11
count= 11
count in mymethod= 12
count= 12

As you can see global variable count is updated in the method and the updated value is retained so that the new object gets that value. At the class level x is declared as global that let each new instance know that x has the scope in the whole code block. In the method mymethod count is again declared as global so that the same count variable is used.

Sharing global variables in multiple Python modules

Global variables in Python can be shared across multiple modules. In the example there is a module Test.py that declares two variables.

x = 0
y = ""

In another module (Display.py) Test.py is imported and values are assigned to the variables that are declared in Test.py.

import Test
def display():
  #assigning values to global variables
  Test.x = 7
  Test.y = "Module"
  print('x=',Test.x, 'y=', Test.y)

Then you can import these modules and display values of the variables directly or by calling the function display of Display.py module.

import Display
import Test
Display.display()
print(Test.x)
print(Test.y)

Output

x= 7 y= Module
7
Module

Non-local variables in Python

Non-local variables are created using nonlocal keyword in Python. The nonlocal keyword causes the variable to refer to previously bound variables in the nearest enclosing scope excluding globals.

nonlocal keyword is added in Python 3.

Python nonlocal keyword example

nonlocal keyword is used with variables in nested functions where the variable is in outer scope, by making variable nonlocal it can be accessed in nested function. Let’s clarify it with an example.

In the example there is a function myfunction() where a variable count is declared. In the nested function increment() value of count is incremented. This results in an error ‘UnboundLocalError: local variable 'count' referenced before assignment’ because count variable is in the scope of outer method.

def myfunction():
  count = 0
  #nested function
  def increment():
    count += 1
    return count
  # calling nested function
  print('count is-', increment())
  print('count is-', increment())
  print('count is-', increment())

myfunction()

Output

  File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 12, in <module>
    myfunction()
  File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 8, in myfunction
    print('count is-', increment())
  File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 5, in increment
    count += 1
UnboundLocalError: local variable 'count' referenced before assignment

To ensure that nested function has access to the variable in the enclosing scope, you can use nonlocal keyword with variable in the body of nested function.

def myfunction():
  count = 0

  def increment():
    nonlocal count
    count += 1
    return count
  # calling nested function
  print('count is-', increment())
  print('count is-', increment())
  print('count is-', increment())

myfunction()

Output

count is- 1
count is- 2
count is- 3

That's all for this topic Local, Non-local And Global Variables in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Namespace And Variable Scope in Python
  2. Multiple Inheritance in Python
  3. Method Overloading in Python
  4. self in Python
  5. Getting Substring in Python String

You may also like-

  1. Passing Object of The Class as Parameter in Python
  2. Class And Object in Python
  3. List Comprehension in Python With Examples
  4. How to Sort HashSet in Java
  5. Thread Priorities in Java Multi-Threading
  6. String in Java Tutorial
  7. Autowiring in Spring Using @Autowired and @Inject Annotations
  8. Sequence File in Hadoop

2 comments:

  1. For the example of the "Python global variable in class example". Can't the class variable be accessed as self.count ? (why is global required)?
    When declaring variable as global inside a class?
    i.e. class MyClass():
    global count
    Does this mean we are trying to access the variable defined in the file(with global scope).

    ReplyDelete
    Replies
    1. In the article itself it says "Suppose you want to have a global variable which has to retain its updated value for all the class instances so that any new object gets the updated value." so it is retaining updated value for all class instances. self in Python is a reference to the current object (just like this in Java) so self won't work in this scenario.

      Delete