Analogue to Signature.replace, in frozen dataclasses

In the Signature and Parameter classes of the inspect module, which are immutable, you can use the replace method which creates a copy of the given object with some changes by parameters.
Is there a common, canonical or otherwise simple equivalent for dataclasses having been passed frozen=True ? I have an idea using dataclasses.asdict but I’m not sure it’s the most optimized.

You mean this?

Oh, right :sweat:
I would have expected it to be a method rather than a function, but I should have thought about it when seeing as_dict… Thanks a lot !
Would you know if there is any counter-indication as to writing replace = dataclasses.replace inside the class body ? so that it becomes a method for the class

Lol yeah so I erroneously called it a method in my reply…it’s got the correct signature to become a boundmethod (first arg is the object) so I don’t see why you couldnt assign it to an attribute in your dataclass and then get a bound method from it on an instance…

1 Like

The reason it’s a function and not a method is that this way it doesn’t conflict with any field you may wish to add to the dataclass. You could make it a method if you wanted to.

2 Likes