Global Keyword in Python

Global-Keyword-Python
Global-Keyword-Python

Introduction 

While writing Python code, you might have come across an instance where you want the accessibility of a variable to be restricted to a particular code block. The accessibility of the variables is controlled by limiting the scope of the variable. In this case, the variable will only be visible and accessible by the code block in its scope. The two types of scopes available in Python are Local Scope and Global Scope.

In this blog, we will be covering the concept of global scope in detail, along with some examples.

Local Scope in Python

When a variable is declared inside the function’s body, the accessibility of the variable is restricted only inside the function block. This type of scope is called local scope. The variable with the local scope is called the local variable.

Let’s look at an example to understand the local scope.

def func():
# local scope
name = "Coding Ninjas"
print(name)
func()

Output:

"Coding Ninjas"

Now let’s see what happens when we try to access the variable name outside the function.

def func():
 # local scope
 name = "Coding Ninjas"
func()
print(name)

Error:

In this case, an error occurs because the variable “name” does not exist outside the function and cannot be accessed outside the function.

Global Scope in Python

In Python, a variable declared outside the function is said to have a global scope. The variable can now be accessed both inside and outside of the function. The variable with global scope is called the global variable.

A variable declared in the top-level segment of the python program is said to have a global scope and can be used anywhere in the program. Let’s now look at an example to understand the global scope.

blog banner 1
# global scope
name = "Coding Ninjas"
def func():
print(name)   
func()

Output:

"Coding Ninjas"

Global and Local Variable with the same name

In Python, it is possible to have a global and local variable with the same name. In this case, the local variable is used inside the function, and outside the function, the global variable is used. Let’s see an example to understand this scenario.

# global variable
s = "Global Variable"
def func():
 # local variable
s = "Local Variable"
print("I am a " + s)
func()
print("I am a " + s)

Output:

I am a Local Variable
I am a Global Variable

In the above program, both global and local variables have the same name, “s.” We get a different result on printing the value of “s” because the variables have been declared in different scopes, i.e., the local scope inside func() and global scope outside func().

When we print the value of the variable inside func(), it prints the value of the local variable. And, when we print the value of the variable outside func(), it prints the value of the global variable.

Global Keyword in Python

In Python, the global keyword is used to modify the variable outside of the current scope.  Global keyword is used inside a function when the variable has to be updated using the variable’s initial value. However, it is not required to print or access the variables in the function.

Let’s see what happens when we try to update a global variable inside the function by using the variable’s initial value.

# global scope
name = "Coding"
def func():
name = name + " Ninjas"
print(name)   
func()

Error:

An error is obtained as Python treats “name” as a local variable, and we have not defined any local variable “name” inside the func(). To solve this error, we use the global keyword.

# global scope
name = "Coding"
def func():
 #global keyword used
 global name
 # name updated
 name = name + " Ninjas"
 print("Inside function: " + name)   
func()
print("Outside function: " + name)  

Output:

Inside function: Coding Ninjas
Outside function: Coding Ninjas

Notice that the change has also occurred on the global variable outside the function.

Rules of Global Keyword in Python

The basic rules for the global keyword in Python are:

  • A variable created inside a function is local by default unless explicitly declared global.
  • A variable declared outside of a function is global by default. 
  • The global keyword is used to make a variable global inside a function.
  • The use of the global keyword outside of a function is unnecessary.

Global Variables Across Python Modules

In Python, a file containing the Python statements and definitions is called a module. To share global variables across different modules within the same program, we create a single module (often named config.py). This module holds the global variables and shares the information across Python modules within the same program.

We import the config module in all the required modules to share global variables across different modules within the same program. This module now becomes available as a global name. Only one instance of each module is present, so any changes made to the module object are reflected everywhere.

Let’s see an example to understand how global variables are shared across the python modules.

Create a config.py file to store the global variables

# global variables of name and year stored
name = "Coding"
year = 2020

Create a update.py file to update the global variables

# import config module
import config
# modify the global variables
config.name = "Coding Ninjas"
config.year = 2021

Create a main.py file to print the changed value of global variables

# import both config and update module
import config
import update
# print the updated value
print("Modified value of name: " + config.name)
print("Modified value of year: ", config.year)

Output:

Modified value of name: Coding Ninjas
Modified value of year: 2021

Global Variables in Nested Functions 

To use global inside a nested function, we must declare a variable with a global keyword inside a nested function. Here is how global variables are used in a nested function.

def func():

year = 2020
def change():
global year
year = 2020
# local variable year printed
print("Before changing local variable year: ", year)
    change()
# local variable year printed
 print("After changing local variable year: ", year)
func()
# global variable year printed
print("Global variable year: ",year)

Output:

Before changing local variable year:  2020
After changing local variable year:  2020
Global variable year:  2021

In the above program, a global variable is declared inside the nested function change().

Inside func(), “year” has no effect on the global keyword. Before and after calling change(), the variable “year” takes the value of the local variable, i.e., 2020. 

Outside of func(), the variable year will take value defined in change()  i.e 2021. This is because the global keyword has been used in “year” to create a global variable inside the change().

If any changes have been made inside the change(), the changes appear outside the local scope, i.e., func().

Frequently Asked Questions

How do you declare a global variable in Python? 

A variable declared outside of a function is global by default, and to make a variable global inside a function; the global keyword is used.

How to use a global variable in another Python file?

To use a global variable in another Python file, create a file to hold the global variables and import this file to the required destination.

  What happens if there is a local variable with the same name as the global variable you want to access?

In this case, the global variable is shadowed, and the local variable is given preference.

What is the lifetime of a global variable and a local variable?

 The lifetime of a Global variable is the entire program run and the lifetime of a Local variable is their function’s run.

What is the use of the globals() method in Python?

The global symbol table stores all information related to the program’s global scope and is accessed in Python using the globals() method.

Key Takeaways

That was all about the global keyword in Python. In this blog, we covered the concept of local scope, global scope, rules of the global keyboard in Python, accessing the global variables across Python files, and some FAQs related to the global keyboard in Python.

Now that you know what a global keyword in Python is, go ahead and attempt some questions based on them on our CodeStudio Platform!

Don’t stop here. Check out our Python-guided path to learn Python from scratch. We hope you found this blog useful. Feel free to let us know your thoughts in the comments section. 

By- Hari Sapna Nair