Open In App

Python – globals() function

Last Updated : 29 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, the globals() function is a built-in function that returns a dictionary representing the current global symbol table. In this article, we will see the Python globals() function.

globals() Function in Python

Python globals() function is a built-in function in Python that returns the dictionary of the current global symbol table. 

Symbol table: A symbol table is a data structure that contains all necessary information about the program. These include variable names, methods, classes, etc. The global symbol table stores all information related to the program’s global scope and is accessed in Python using the globals() method. The functions, and variables that are not associated with any class or function are stored in global scope.

Python globals() Syntax

Syntax: globals()

Parameters: No parameters required.

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.

Python3




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}

Example 2: Python globals() Function Demonstration

In this example, we are using globals() function to demonstrate about globals() function in Python.

Python3




# Python3 program to demonstrate global() function
# global variable
a = 5
 
def func():
    c = 10
    d = c + a
     
    # Calling globals()
    globals()['a'] = d
    print (a)
     
# Driver Code   
func()


Output

15



Example 3: Modify Global Variable Using Globals in Python

In this example, we are using globals() to modify global variables in Python.

Python3




# Python3 program to demonstrate global() function
 
# global variable
name = 'gautam'
 
print('Before modification:', name)
 
# Calling global()
globals()['name'] = 'gautam karakoti'
print('After modification:', name)


Output

Before modification: gautam
After modification: gautam karakoti



Note: We can also change the value of global variables by using globals() function. The changed value also updated in the symbol table.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads