Python 3.13 的新复制替换
数据类复制替换
数据类首次在 Python 3.7 版本中引入,通过自动生成特殊方法,即双下方法 ,显著简化了类的工作。数据类的 replace 方法从数据类的副本创建一个新的数据类实例,但具有更新的字段。如果您想复制一个具有许多字段的数据类实例,但其中大多数字段没有变化,这很有用。
from dataclasses import dataclass, replace
@dataclass
class Employee:
name: str
deparment: str
user1 = Employee('Jane', 'Accounting')
user2 = replace(user1, name='John')
print(user2)
# Employee(name='John', department='Accounting')
现在我们有两个数据类,user1 和 user2,分别代表会计部门的 Jane 和 John。在 Python 3.13 之前,replace 只适用于数据类;如果您尝试将其应用于普通类,则会引发类型错误。
注意一点,当处理标记为 init=False 的更复杂的数据类字段时,它们不会被复制。这意味着新的实例可以调用 __init__ 方法,进而确保也会调用任何 __post_init__ 方法。
from dataclasses import dataclass, field
@dataclass
class Total:
first: int
second: int
result: int = field(init=False)
def __post_init__(self):
self.result = self.first + self.second
total = Total(1, 2)
new_total = replace(total, second=3)
print(new_total.result)
# 4
当然,这假设了此类字段的计算是在 __post_init__ 方法中进行的。如果不是这样,则需要自定义一个 replace 方法。
Python 3.13 的新复制替换
Python 最新稳定版本 3.13 中引入了一个新特性,即 copy 模块的 replace 方法。
这个新方法支持并扩展了从数据类到命名元组以及任何具有自己的 __replace__ 双下划线方法的类的 replace 方法。
from dataclasses import dataclass
from copy import replace # new method
@dataclass
class Employee:
name: str
deparment: str
user1 = Employee('Jane', 'Accounting')
# the new replace method supports dataclasses
user2 = replace(user1, name='John')
print(user2)
# Employee(name='John', department='Accounting')
命名元组的复制和替换
Python 的命名元组是使用标准库中的 collections.namedtuple() 或带有类型注解的字段 typing.NamedTuple 创建的轻量级数据结构。命名元组结合了不可变性的优点和命名字段的便捷性。在性能或内存效率重要的情况下,命名元组通常比数据类更受欢迎。
collections.namedtuple() 工厂函数早已是 Python 3 版本的一部分,而带有类型注解的版本是在 3.5 版本中随着新的 typing 库一起添加的。一个常见的用例是表示来自 CSV 文件或 API 响应的数据。不可变性确保数据不会被意外更改,而通过按名称访问字段,代码的可读性和可维护性得到了增强。
当然,我们经常处理数据是因为我们实际上确实想更改它,而 copy.replace 提供了一种方便的方法来复制带有更新字段值的命名元组,就像之前使用数据类一样。
from copy import replace
from typing import Any, NamedTuple
class Response(NamedTuple):
status: int
payload: dict[str, Any] | None
processed: bool = False
unprocessed_resp = Response(200, {"payload": "values"})
# do some processing
processed_resp = replace(unprocessed_resp, processed=True)
print(processed_resp)
# Response(status=200, payload={'payload': 'values'}, processed=True)
自定义替换方法
The copy.replace 方法还允许定义自己的 __replace__ 方法的类在复制时更新字段值。这将为除了数据类和命名元组之外的对象打开复制和替换功能。
from copy import replace
from typing import Any
class InventoryItem:
def __init__(self, name: str, quantity: int, price: float) -> None:
self.name: str = name
self.quantity: int = quantity
self.price: float = price
def __replace__(self, **changes: dict[str, Any]):
_attrs = self.__dict__.copy()
_attrs.update(changes)
return InventoryItem(**_attrs)
def __repr__(self):
return (
f"{self.__class__.name}"
f"({', '.join([str(k) + '=' + str(v) for k, v in self.__dict__.items()])})"
)
item = InventoryItem("widget", 10, 0.99)
print(item)
# InventoryItem(name=widget, quantity=10, price=0.99)
item_update = replace(item, **{"quantity": 5})
print(item_update)
# InventoryItem(name=widget, quantity=5, price=0.99)
__replace__ 方法通过复制原始实例的特殊 __dict__ 属性并创建和实例化一个新对象来创建一个新的 InventoryItem 类实例。
现在,让我们给每个 InventoryItem 添加成本,通过将价格乘以数量。因为 cost 不会是 __init__ 方法的参数,所以重要的是要注意在实例化新对象之前必须从 __dict__ 复制中删除它。
from copy import replace
from typing import Any
class InventoryItem:
def __init__(self, name: str, quantity: int, price: float) -> None:
self.name: str = name
self.quantity: int = quantity
self.price: float = price
self.cost = self.quantity * self.price
def __replace__(self, **changes: dict[str, str]):
_attrs = self.__dict__.copy()
_attrs.pop("cost")
_attrs.update(changes)
return InventoryItem(**_attrs)
def __repr__(self):
return (
f"{self.__class__.__name__}"
f"({', '.join([str(k) + '=' + str(v) for k, v in self.__dict__.items()])})"
)
item = InventoryItem("widget", 10, 0.99)
print(item)
# InventoryItem(name=widget, quantity=10, price=0.99, cost=9.9)
item_update = replace(item, **{"quantity": 5})
print(item_update)
# InventoryItem(name=widget, quantity=5, price=0.99, cost=4.95)
摘要
Python 3.13 的新 copy.replace 功能已将功能从数据类扩展到命名元组以及任何定义了自己的 __replace__ 方法的类。此功能使复制和更新对象变得更加容易、安全,并且可以在更复杂的类的情况下进行自定义。