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.



Python – globals() function

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.

Similar Reads

globals() Function in Python

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

Python globals() Syntax

Syntax: globals() Parameters: No parameters required....

Contact Us