globals() Function in PythonThe 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.
globals()
Parameters
globals() function does not take any arguments.Return Value
x = 10
y = 20
print(globals())
Output (partial example)
{'__name__': '__main__', '__builtins__': {...}, 'x': 10, 'y': 20}
Explanation
globals() includes global variables such as x and y.globals()a = 50
b = 30
g = globals()
print(g['a'])
print(g['b'])
Output
50
30
Explanation
globals() returns a dictionary stored in variable g.globals() Inside a Functionx = 100
def show():
print(globals()['x'])
show()
Output
100
Explanation
globals() can access variables defined at the global level.globals()x = 10
globals()['x'] = 50
print(x)
Output
50
Explanation
x is changed using the dictionary returned by globals().name = "Rahul"
course = "BCA"
def display():
g = globals()
print(g['name'])
print(g['course'])
display()
Output
Rahul
BCA
Explanation
globals().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()
globals()The globals() function is useful for:
globals() is a built-in Python function.