I want to modify a dataclass(dataclass_json) in a map/lambda. With dictionaries you can perform a dict.update({"key": "value"}) within a lambda, but how does one update a dataclass's value without:
MyDataClass.name = "class name" # this works outside a lambda
(Example below is the incorrect syntax I know)
repositories_list: List[MyDataClass]
_ = list(map(lambda repository: repository.name = my_func(repository), repositories_list))
Of course I can't just use =, so how's this done?
You can access setattr
, the function that does the actual work during an attribute assignment, directly:
list(map(lambda r: setattr(r, "name", my_func(repository)), repositories_list))
This pattern is not dataclass-specific, it works with any python object.
Solved it with replace from dataclasses
from dataclasses import replace
repositories_list = list(map(lambda repository: replace(repository, name=my_func(repository)), repositories_list))
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.