Last Updated : 28 Apr, 2025
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() Syntaxglobals()
Return Value: The globals() function returns a dictionary where:
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.
Python
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:
In this example, we are using globals() function to demonstrate about globals() function in Python.
Python
a = 5
def func():
c = 10
d = c + a
globals()['a'] = d
print (a)
func()
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 PythonIn this example, we are using globals() to modify global variables in Python.
Python
name = 'Brijkant'
print('Before modification:', name)
globals()['name'] = 'Brijkant Yadav'
print('After modification:', name)
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4