Python - globals() function
In Python, the globals() function is used to return the global symbol table - a dictionary representing all the global variables in the current module or script. It provides access to the global variables that are defined in the current scope. This function is particularly useful when you want to inspect or modify global variables dynamically during the execution of the program.
Python globals() Syntax
globals()
Return Value: The globals() function returns a dictionary where:
- Keys: Variable names (as strings) that are defined globally in the script.
- Values: The corresponding values of those global variables.
Examples of globals() function
Example 1: How Globals Python Method Works
In this example, we are using the globals() function to display the global symbol table before any variables are defined as well as displaying the global symbol table after variables are defined.
print(globals())
print("")
p,q,r,s=10,100,1000,10000
print(globals())
Output
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':
<class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {},
'__builtins__': <module 'builtins' (built-in)>}
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':
<class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {},
'__builtins__': <module 'builtins' (built-in)>, 'p': 10, 'q': 100, 'r': 1000,'s':10000}
Explanation:
- The first print(globals()) displays the global symbol table, which includes built-in variables and functions.
- After defining the variables p, q, r, and s, the second print(globals()) shows the updated global symbol table, now including these variables with their assigned values.
Example 2: Python globals() Function Demonstration
In this example, we are using globals() function to demonstrate about globals() function in Python.
a = 5
def func():
c = 10
d = c + a
globals()['a'] = d
print (a)
func()
Output
15
Explanation: This code demonstrates how to modify a global variable inside a function using globals(). Initially, a = 5 is set globally. Inside the function, the local variables c and d are calculated, and the global variable a is updated to the value of d (15) using globals(). Finally, the updated value of a is printed.
Example 3: Modify Global Variable Using Globals in Python
In this example, we are using globals() to modify global variables in Python.
name = 'Brijkant'
print('Before modification:', name)
globals()['name'] = 'Brijkant Yadav'
print('After modification:', name)
Output
Before modification: Brijkant After modification: Brijkant Yadav
Explanation: This code demonstrates modifying a global variable using globals(). Initially, name = 'Brijkant' is set. Using globals()['name'] = 'Brijkant Yadav', the value of name is updated to 'Brijkant Yadav'. The updated value is then printed.