I'm interested to use dataclass as the syntax is shorter than attr. However I can't find a shortcut that provides the API to evolve it, using eg the following code:
@dataclass
class AB(object):
a: int = 1
b: int = 2
AB().evolve(b=3)
result = AB(a=1, b=3)
Is it easy to find an out-of-the-box replacement? or to implement it on my own?
The dataclasses.replace()
function is roughly equivalent to the attr.evolve()
function.
Usage example based on your code:
import dataclasses
from dataclasses import dataclass
@dataclass
class AB(object):
a: int = 1
b: int = 2
ab_object = AB()
another_ab_object = dataclasses.replace(ab_object, b=3)
print(ab_object)
# Output: AB(a=1, b=2)
print(another_ab_object)
# Output: AB(a=1, b=3)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.