Python globals() Function

Python3 内置函数Python3 Built-in Functions


globals()It is a built-in function in Python used to return the dictionary of variables in the current global scope.

globals()Returns a dictionary containing all global variables of the current module. This dictionary contains all imported modules, defined functions, classes, and global variables.

Word Definition: globals 意为"全局的",表示全局作用域中的变量。


Basic Syntax and Parameters

Syntax Format

globals()

Parameter Description

  • No parameters

Function Description

  • Return Value: Returns a dictionary containing variables in the global scope.

Example

Example 1: View Global Variables

Example

# Define some global variables
global_var = 100
global_list = [1, 2, 3]

import math
import os

# Get the global variable 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 if the variable exists
print('global_var' in g)  # Output: True
print('unknown' in g)     # Output: False

Expected Output:

变量数量: ...
global_var: 100
math: <module 'math'>
os: <module 'os'>
True
False

Code Analysis:

  1. globals() returns all global variables of the current module.
  2. Includes imported modules, functions, classes, etc.

Example 2: Dynamically Operate Global Variables

Example

# Dynamically create global variables
globals()['dynamic_var'] = "Hello"
print(dynamic_var)  # Output: Hello

# Batch create variables
for i in range(3):
    globals()[f'var_{i}'] = i * 10

print(var_0, var_1, var_2)  # Output: 0 10 20

# Use globals() in a function
def test():
    g = globals()
    g['x'] = 999
    print(f"In function: x = {x}")

test()
print(f"Outside function: x = {x}")  # Output: x = 999

Expected Output:

Hello
0 10 20
在函数中: x = 999
在函数外: x = 999

You can dynamically modify global variables, but this is generally not recommended.

globals()Mainly used for debugging and dynamic programming.


Python3 内置函数Python3 Built-in Functions


Other Extensions