Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to evolve a dataclass in python?

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 e.g. 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?

like image 946
tribbloid Avatar asked Mar 03 '23 22:03

tribbloid


1 Answers

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)
like image 181
Xukrao Avatar answered Mar 12 '23 04:03

Xukrao