BlogsDope image BlogsDope

Python globals() function

Feb. 28, 2021 PYTHON FUNCTION 1392

Python provides a large number of utility functions to perform various operations and the Python globals() function is one such method. The globals() method is a built-in function and it returns a dictionary of the current global symbol table.

globals() Syntax

The following is the syntax of the globals() method:

​globals()

globals() Parameters

The globals() method does not take any parameter as an argument.

globals() Return Value

The globals() function returns a dictionary of the current global symbol table. This dictionary consists of all the global variables as well as other symbols for the current program that are stored in the current global symbol table. 

What is a Symbol Table?

A symbol table is a data structure that is maintained by the compiler and it contains all the necessary information about the program such as variable names, methods, classes, etc. There are two kinds of symbol tables" 
  1. Local symbol table: Local symbol table contains all the information related to the local scope of the program, and is accessed in Python using locals() method. A local scope can be within a function, within a class, etc.
  2. Global symbol table: A Global symbol table contains all the information related to the global scope of the program, and is accessed in Python using globals() method. The global scope consists of all functions, variables that are not associated with any class or function.

globals() Examples

Example 1:
In the below example we can see that the globals() method can only access the global variables and not the local variable.
# global variables
a = 5
b = 10

def myFunc():
    # local variable
    s = 100
print(globals())

Output:

​{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__spec__': None, '__annotations__': {},
'__builtins__': <module 'builtins' (built-in)>,
'a': 5, 'b': 10, 'myFunc': <function myFunc at 0x7f034180ee50>}

Example 2:
Since the global symbol table stores all global variables, we can access and modify the value of a global variable using the globals() function.

# global variables
a = 5
print("Before change the value of a is:",a)

globals()['a'] = 10
print("After change the value of a is:",a)

Output:

Before change the value of a is: 5
After change the value of a is: 10

In this way we have seen the working of the Python globals() function and how it can be used to access the global variables and the global symbol table.


Liked the post?
Zealous Learner.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).