Search code examples
python-3.ximmutabilitycopy-constructorpython-3.8python-attrs

How can I get a modified copy of a immutable object?


How can I get a modified copy of a immutable object?

I.e. how could some_magical_method look like in this snipped?

import attr

@attr.s(frozen=True, slots=True)
class Config:
    param1: int = attr.ib()
    param2: str = attr.ib()

my_base_config = Config(param1=1, param2="2")
my_derived_config = my_base_config.some_magical_method(param2="two")

print(my_derived_config.param1) # output: 1
print(my_derived_config.param2) # output: two

Background: I want to use immutable objects for my configuration. But I also want to avoid code duplication when dealing with very similar configurations, e.g. for unit tests


Solution

  • attrs has a function specifically for you: https://www.attrs.org/en/stable/api.html#attr.evolve

    Since it takes the instance as a first arguments you can use it to define a method too:

    @attr.s
    class C:
        some_magical_method = attr.evolve