Skip to content

A way to copy an instance while replacing some fields #42

@bluetech

Description

@bluetech

When programming with an immutable/frozen data structure (which I personally prefer to do whenever it's reasonable), perhaps the most common operation is to replace some subset of the fields with new values, returning a new instance. It would be nice if dataclasses had similar functionality, for frozen classes at least.

Some prior art:


Python 3 dict:

a = {'key1': 'value1', 'key2': 'value2'}
b = {**a, 'key1': 'VALUE1'}

namedtuple _replace:

NT = namedtuple('NT', ('field1', 'field2'))
a = NT(field1='value1', field2='value2')
b = a._replace(field1='VALUE1')

attrs evolve:

@attr.s
class C:
     field1 = attr.ib()
     field2 = attr.ib()
a = C(field1='value1', field2='value2')
b = attr.evolve(a, field1='VALUE1')

Kotlin data class copy:

data class C(val field1: String, val field2: String)
val a = C(field1 = "value1", field2 = "value2")
val b = a.copy(field1 = "VALUE1")

Clojure record assoc:

(defrecord R [field1 field2])
(def a (R. "value1" "value2"))
(def b (assoc a :field1 "VALUE1"))

There are of course other example, but I think this shows the variety of names.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions