Python globals() Function
globals() is a built-in Python function that returns the dictionary of variables in the current global scope.
globals() It returns a dictionary containing all global variables of the current module. This dictionary includes all imported modules, defined functions, classes, and global variables.
Word meaning: globals 意为"全局的",表示全局作用域中的变量。
Basic syntax and parameters
Syntax format
globals()
Parameter Description
- No parameters
Function description
- Return Value: returns a dictionary containing the variables in the global scope.
Example
Example 1: viewing global variables
Example
# Define some global variables
global_var = 100
global_list = [1, 2, 3]
import math
import os
# Get the global variables dictionary
g = globals()
print(f"Number of variables: {len(g)}")
# View a specific variable
print(f"global_var: {g.get('global_var')}")
print(f"math: {g.get('math')}")
print(f"os: {g.get('os')}")
# Check whether a variable exists
print('global_var' in g) # Output: True
print('unknown' in g) # Output: False
global_var = 100
global_list = [1, 2, 3]
import math
import os
# Get the global variables dictionary
g = globals()
print(f"Number of variables: {len(g)}")
# View a specific variable
print(f"global_var: {g.get('global_var')}")
print(f"math: {g.get('math')}")
print(f"os: {g.get('os')}")
# Check whether a variable exists
print('global_var' in g) # Output: True
print('unknown' in g) # Output: False
Expected output:
变量数量: ... global_var: 100 math:os: True False
Code analysis:
- globals() returns all global variables of the current module.
- It includes imported modules, functions, classes, and so on.
Example 2: dynamically manipulating global variables
Example
# Create a global variable dynamically
globals()['dynamic_var'] = "Hello"
print(dynamic_var) # Output: Hello
# Create variables in bulk
for i in range(3):
globals()[f'var_{i}'] = i * 10
print(var_0, var_1, var_2) # Output: 0 10 20
# Use globals() inside a function
def test():
g = globals()
g['x'] = 999
print(f"Inside the function: x = {x}")
test()
print(f"Outside the function: x = {x}") # Output: x = 999
globals()['dynamic_var'] = "Hello"
print(dynamic_var) # Output: Hello
# Create variables in bulk
for i in range(3):
globals()[f'var_{i}'] = i * 10
print(var_0, var_1, var_2) # Output: 0 10 20
# Use globals() inside a function
def test():
g = globals()
g['x'] = 999
print(f"Inside the function: x = {x}")
test()
print(f"Outside the function: x = {x}") # Output: x = 999
Expected output:
Hello 0 10 20 在函数中: x = 999 在函数外: x = 999
Global variables can be modified dynamically, though this is usually not recommended.
globals() It is mainly used for debugging and dynamic programming.
Python3 built-in function