Fundamentals 5 min read

Understanding Shallow Copy in Python: Explanation, Use Cases, and Code Examples

This article explains the concept of shallow copy in Python, contrasts it with deep copy, outlines ten practical scenarios such as parameter passing, data backup, error recovery, and parallel processing, and provides a comprehensive code example demonstrating how to use the list .copy() method in each case.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Understanding Shallow Copy in Python: Explanation, Use Cases, and Code Examples

Shallow copy and deep copy are two different data copying methods in Python. A shallow copy creates a new object but its elements are references to the original object's elements, so changes affect both.

Typical scenarios where shallow copy is useful include:

Parameter passing in interface testing to avoid unintended modifications.

Data backup for quick creation of a shallow replica.

Error recovery by preserving the original state.

Parallel processing to provide separate copies for threads.

Test case generation for isolated test data.

Data simulation for generating mock data.

Log recording to keep original parameter values.

Data validation by comparing original and returned data.

State saving during automation.

Configuration management to revert changes.

Code example demonstrating these use cases:

import threading
import copy
# 1. 参数传递
def pass_parameter(data):
    data.append(7)
    return data
original_data = [1, 2, 3, 4, 5]
passed_data = pass_parameter(original_data.copy())
print("传递后的数据:", passed_data)
# 2. 数据备份
original_data = [1, 2, 3, 4, 5]
backup_data = original_data.copy()
original_data.append(6)
print("原始数据:", original_data)
print("备份数据:", backup_data)
# 3. 错误恢复
original_data = [1, 2, 3, 4, 5]
error_data = original_data.copy()
original_data.append(6)
original_data = error_data
print("恢复后的数据:", original_data)
# 4. 并行处理
original_data = [1, 2, 3, 4, 5]
thread1 = threading.Thread(target=lambda: process_data(original_data.copy()))
thread2 = threading.Thread(target=lambda: process_data(original_data.copy()))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
# 5. 测试用例
def test_case(data):
    data.append(7)
    return data
original_data = [1, 2, 3, 4, 5]
test_data = test_case(original_data.copy())
print("测试用例后的数据:", test_data)
# 6. 数据模拟
original_data = [1, 2, 3, 4, 5]
simulated_data = [x * 2 for x in original_data.copy()]
print("模拟后的数据:", simulated_data)
# 7. 日志记录
original_data = [1, 2, 3, 4, 5]
logged_data = original_data.copy()
logged_data.append("接口调用成功")
# 8. 数据验证
def validate_data(data):
    if len(data)!= 5:
        return False
    return True
original_data = [1, 2, 3, 4, 5]
validated_data = validate_data(original_data.copy())
print("验证后的数据:", validated_data)
# 9. 状态保存
original_data = [1, 2, 3, 4, 5]
saved_data = original_data.copy()
original_data.append(6)
# 10. 配置管理
original_config = {"username": "admin", "password": "123456"}
configured_data = original_config.copy()
configured_data["username"] = "user"
original_config = configured_data
print("配置:", original_config)
pythonData StructuresProgramming Fundamentalsshallow copyCopying
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.