Python globals() Method – [With Examples]

In this tutorial we will learn about python globals() method and its uses with examples.

Python globals() Method

What is Python globals() Method?

The globals() method returns the dictionary of the current global symbol table.

What is the symbol table in python?

A symbol table is a data structure that contains all the necessary information regarding the program that includes variable names, functions, methods, classes, etc.

The syntax of globals() method is:


globals() Parameters

The globals() method does not take any parameter.

Let us check some examples of globals() method.

If we use the globals() method in the python interpreter, it will show as all the global variables and other default symbols declared by python.

Example 1: Using globals() with python interpreter.

>>> globals()

When you run the above program, it will display the following output on the python interpreter.


{‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <class ‘_frozen_importlib.builtinimporter’=“”>, ‘__spec__’: None, ‘__annotations__’: {}, ‘__builtins__’: <module ‘builtins’=“” (built-in)=“”>}</module></class>

Example 2: How to use globals() method in python?

# global variable
num = 10
def User_Func():
a = 5
b = a + num
# Calling globals() method
globals()[‘num’] = b
# Calling the User_Func



We can also modify the global variable using the globals() method.

Example 3: Modify global variable using globals() method.

name = “Python”
globals()[‘name’] = ‘PythonScholar’
print(‘The new name is:’, name)

The output will be as follow:

The new name is: PythonScholar

We can also check global variables of other python libraries using the globals() method.

Example 4: using globals() method with python libraries.

import math
from pprint import pprint

The output will be as follow:

{‘__annotations__’: {},
‘__builtins__’: <module ‘builtins’=“” (built-in)=“”>,
‘__doc__’: None,
‘__file__’: ‘’,
‘__loader__’: <class ‘_frozen_importlib.builtinimporter’=“”>,
‘__name__’: ‘__main__’,
‘__package__’: None,
‘__spec__’: None,
‘math’: <module ‘math’=“” (built-in)=“”>,
‘pprint’: <function pprint=“” at=“” 0x7f340321b1f0=“”>}</function></module></class></module>

As you can see, it returns all the global variables and default symbols of imported python libraries.

Rules of Python globals()

The  globals() method returns the result in dictionary format of the current global symbol table.