Notes

`globals()` Function in Python [ English ]

< Prev Next >

globals() Function in Python

1. Introduction

The globals() function in Python is a built-in function that returns a dictionary containing the global symbol table. The global symbol table stores information about all global variables, functions, and objects defined at the global level of a program.

Global variables are variables that are defined outside any function and can be accessed throughout the entire program.

The globals() function is useful for inspecting, accessing, and modifying global variables dynamically.

2. Syntax

globals()

Parameters

Return Value

3. Basic Example

x = 10
y = 20

print(globals())

Output (partial example)

{'__name__': '__main__', '__builtins__': {...}, 'x': 10, 'y': 20}

Explanation

4. Accessing Global Variables Using globals()

a = 50
b = 30

g = globals()

print(g['a'])
print(g['b'])

Output

50
30

Explanation

5. Using globals() Inside a Function

x = 100

def show():
    print(globals()['x'])

show()

Output

100

Explanation

6. Modifying Global Variables Using globals()

x = 10

globals()['x'] = 50

print(x)

Output

50

Explanation

7. Practical Example

name = "Rahul"
course = "BCA"

def display():
    g = globals()
    print(g['name'])
    print(g['course'])

display()

Output

Rahul
BCA

Explanation

8. Difference Between globals() and locals()

Feature globals() locals()
Purpose Returns global variables Returns local variables
Scope Entire program Current function or block
Return type Dictionary Dictionary

Example:

x = 10

def test():
    y = 5
    print("Global:", globals())
    print("Local:", locals())

test()

9. Uses of globals()

The globals() function is useful for:

10. Summary

< Prev Next >