What is the purpose of global keywords in python?
In Python, the global keyword is used to declare that a variable inside a function is referring to a global variable defined outside the function rather than creating a new variable with the same name as the global variable inside the function. This allows the function to modify the value of the global variable instead of creating a new local variable with the same name. The global keyword is used to access and modify global variables from within a function, and it is especially useful when working with larger programs or modules.
Must Read, Divmod in Python
In Python, the global keyword is used to modify the variable outside of the current scope. The 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.
Python
# 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.
Also see, Merge Sort Python
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
Use of Global Keyword
In Python, the global keyword is used to indicate that a variable declared inside a function should be treated as a global variable, rather than a local variable. This means that the variable can be accessed and modified both inside and outside the function. Let us see what we can do without and with global keyword:
-
Without the global keyword: If we define a variable inside a function without using the global keyword, it is treated as a local variable. This means that the variable is only accessible within that function, and any modifications to it won't affect the variable with the same name outside the function
- With the global keyword: When we use the global keyword before declaring a variable inside a function, it tells Python that the variable should be treated as a global variable. This means that the variable can be accessed and modified from both inside and outside the function, affecting the same variable in the global scope
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.
Python
# global scope
name = "Coding Ninjas"
def func():
print(name)
func()
Output
"Coding Ninjas"
Example of Global Keyword in Python
Example 1: Changing global Variable From Inside a Function
It is possible to change the value of a global variable from inside a function in Python by using the global keyword to indicate that the variable should be treated as a global variable, like this:
Python
x = 1
def change_global():
global x
x = 2
change_global()
print(x)
Output
"2"
However, it is generally considered better programming practice to avoid relying on global variables and instead pass values between functions using function arguments and return values.
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
You can practice by yourself with the help of online python compiler.
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.
Python
year = 2020
def func():
def change():
global year
year = 2021
# Local variable year printed
print("Before changing local variable year:", year)
change()
# Local variable year printed
print("After changing local variable year:", year)
# Global variable year printed
print("Global variable year:", year)
func()
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().
Also check out Python Square Root here.
Frequently Asked Questions
What is global keyword in Python?
In Python, the global keyword indicates that a variable declared inside a function should be treated as a global variable rather than a local variable. This allows the variable to be accessed and modified from outside the function.
What is the use of globals ()?
In Python, the globals() function is used to return a dictionary containing all the global variables in the current scope. This can be useful for inspecting or modifying global variables at runtime.
What is globals() in Python?
globals() is a built-in function in Python that returns a dictionary representing the global symbol table. It contains all global variables and their corresponding values accessible from the current scope.
What is global reference in Python?
In Python, a global reference refers to accessing a variable defined in the global scope from within a function or other nested scopes, using the global keyword to modify its value if necessary.
What is global module in Python?
The term may refer to accessing global variables or modules from any part of the program, indicating their accessibility throughout the codebase.
Conclusion
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.
Recommended Readings:
Do check out The Interview guide for Product Based Companies as well as some of the Popular interview problems from top tech companies like Amazon, Adobe, Google, Uber, Microsoft, etc.
Refer to our guided paths on Coding Ninjas Studio to learn more about Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available; take a look at the interview experiences and interview bundle for placement preparations.