Fundamentals 11 min read

Using globals() in Python: Basics, Examples, and Advanced API Automation Techniques

This article explains the Python globals() function, shows how it returns a dictionary of all global variables, and provides numerous practical examples—from retrieving and modifying globals to dynamically configuring test environments and generating test cases for API automation.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Using globals() in Python: Basics, Examples, and Advanced API Automation Techniques

In Python programming, accessing and manipulating variables across scopes is common, and the built‑in globals() function returns a dictionary containing all variables in the current global namespace, enabling dynamic access and modification.

What is globals() ? It is a built‑in function that returns a dict of all global variable names and their values.

How to use globals() ? Simply call the function; it returns the global namespace dictionary.

Example 1: Retrieve global variables list

# Define global variables
name = "张三"
age = 25
print(globals())  # Output the global variables dictionary

Example 2: Modify a global variable

# Define a global variable
score = 90

def update_score():
    global score
    score += 10
    print("函数内分数:", score)

update_score()
print("函数外分数:", score)

Example 3: Dynamically create a variable

# Use globals() to create a new global variable
def create_variable(name, value):
    globals()[name] = value

create_variable("address", "上海市")
print("新创建的地址:", address)

Example 4: Delete a global variable

# Define a global variable
favorite_food = "牛肉"
# Delete the global variable using globals()
 del globals()["favorite_food"]
try:
    print(favorite_food)
except NameError:
    print("变量已被删除")

Example 5: Check if a global variable exists

# Define a global variable
is_student = True

def check_variable_exists(var_name):
    if var_name in globals():
        return True
    else:
        return False

print("变量 is_student 是否存在:", check_variable_exists("is_student"))

Example 6: Dynamically modify a global variable

# Define a global variable
balance = 1000

def withdraw(amount):
    if amount <= globals()["balance"]:
        globals()["balance"] -= amount
        return True
    else:
        return False

if withdraw(500):
    print("取款成功,余额:", balance)
else:
    print("余额不足")

Example 7: Access metadata of a global variable

# Define a global variable
pi = 3.14

def get_type_of_variable(var_name):
    return type(globals()[var_name])

print("变量 pi 的类型:", get_type_of_variable("pi"))

Example 8: Iterate over global variables

# Define global variables
country = "中国"
city = "北京"

for key, value in globals().items():
    if not key.startswith("__"):
        print(key, ":", value)

Example 9: Use globals inside a function

# Define a global variable
message = "欢迎光临"

def greet():
    print(globals()["message"])

greet()

Example 10: Use globals inside a class

# Define a global variable
company = "ABC 公司"

class Employee:
    def __init__(self, name):
        self.name = name
    def show_company(self):
        print("公司名称:", globals()["company"])

emp = Employee("李四")
emp.show_company()

Advanced API automation usage

Example 11: Dynamically configure test environment

# Define environment configurations
DEV_CONFIG = {'host': 'dev.example.com', 'port': 8000}
TEST_CONFIG = {'host': 'test.example.com', 'port': 8000}
PROD_CONFIG = {'host': 'api.example.com', 'port': 443}

environment = 'prod'  # could be 'dev', 'test', or 'prod'
# Set current config using globals()
globals()['CURRENT_CONFIG'] = eval(environment.upper() + '_CONFIG')
print("当前环境配置:", CURRENT_CONFIG)

Example 12: Dynamically load test data

import json

def load_test_data(filename):
    with open(filename, 'r') as file:
        data = json.load(file)
        for key, value in data.items():
            globals()[key] = value

load_test_data('test_data.json')
print("用户名:", USERNAME)
print("密码:", PASSWORD)

Example 13: Dynamically set test steps

# Define a function to set test steps

def set_test_steps(steps):
    for step in steps:
        globals()[step['name']] = step['function']

steps = [
    {'name': 'login', 'function': lambda: print("执行登录步骤")},
    {'name': 'create_account', 'function': lambda: print("执行创建账户步骤")}
]

set_test_steps(steps)
login()
create_account()

Example 14: Dynamically register test hooks

# Define test hooks

def before_all_tests():
    print("测试开始前的准备")

def after_all_tests():
    print("测试结束后的清理")

globals()['before_all_tests'] = before_all_tests
globals()['after_all_tests'] = after_all_tests

before_all_tests()
after_all_tests()

Example 15: Dynamically generate test cases

import unittest

def generate_test_cases(data):
    class DynamicTestCase(unittest.TestCase):
        pass
    for i, item in enumerate(data):
        def test_func(item=item):
            print(f"正在运行测试用例 {item['name']}")
        setattr(DynamicTestCase, f'test_case_{i}', test_func)
    return DynamicTestCase

data = [
    {'name': 'case1', 'description': '测试用例1'},
    {'name': 'case2', 'description': '测试用例2'}
]
DynamicTestCase = generate_test_cases(data)
suite = unittest.TestLoader().loadTestsFromTestCase(DynamicTestCase)
unittest.TextTestRunner().run(suite)

Example 16: Dynamically update test report

import unittest

class TestReportCollector:
    def __init__(self):
        self.test_results = []
    def add_result(self, test_name, result):
        self.test_results.append({'test_name': test_name, 'result': result})

class MyTestCase(unittest.TestCase):
    def test_example(self):
        self.assertEqual(1 + 1, 2)
        collector.add_result('test_example', 'pass')
    def test_fail(self):
        self.assertEqual(1 + 1, 3)
        collector.add_result('test_fail', 'fail')

collector = TestReportCollector()
globals()['collector'] = collector

suite = unittest.TestLoader().loadTestsFromTestCase(MyTestCase)
unittest.TextTestRunner().run(suite)
print("测试报告:")
for result in collector.test_results:
    print(f"{result['test_name']}: {result['result']}")

The examples demonstrate how globals() can enhance flexibility and extensibility in API automation, but excessive use may make code harder to maintain, so it should be applied judiciously.

This article provides conceptual guidance rather than copy‑paste ready code.

PythonAutomationTestingglobalsdynamic-variables
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.