<div dir="ltr"><div class="gmail_extra"><div class="gmail_quote">On Fri, Feb 16, 2018 at 3:38 PM, Ben Lewis <span dir="ltr"><<a href="mailto:benlewisj@gmail.com" target="_blank">benlewisj@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div dir="ltr">I have been using dataclasses package in a pet project of mine. I'm sorry if this issue has already been raised. I came across a situation where I wanted to use the __post_init__ function to initialise some inherited fields from a dataclass with frozen=True. The problem is that because it is frozen, assigning to the field doesn't work. <div><br></div><div>There are two workarounds without changing the base class to frozen=False, which could be in a library.</div><div><br></div><div>1. Use object.__setattr__, this is ugly and not very user or beginner friendly.</div><div>2. Extract __post_init__ out into a factory function. Then it also loses all the advantages of the __post_init__ and InitVar mechanism.</div><div><br></div><div>Both frozen and unfrozen dataclasses should be able to use the same initialisation mechanism for consistency. Being consistent would ease of converting an unfrozen dataclass to a frozen one if the only code that actually modifies the instance is in <span style="color:rgb(34,34,34);font-family:arial,sans-serif;font-size:small;font-style:normal;font-variant-ligatures:normal;font-variant-caps:normal;font-weight:400;letter-spacing:normal;text-align:start;text-indent:0px;text-transform:none;white-space:normal;word-spacing:0px;background-color:rgb(255,255,255);text-decoration-style:initial;text-decoration-color:initial;float:none;display:inline">__post_init__ function</span>.</div><div><br></div><div>I think frozen classes should be able to be mutated during the __post_init__ call. To implements this a frozen dataclass could have a flag to says it's not yet fully initialised and the flag would be checked in the frozen setattr/delattr methods. This flag could be located as a special attribute on the instance or be in a weak reference dict.</div></div></blockquote><div><br></div><div>That's a pretty tricky proposal, and one that's been debated on and off for a long time in other contexts. And that flag would somehow have to be part of every instance's state.<br><br></div><div>In general the right way to initialize an immutable/frozen object is not through __init__ but through __new__ -- have you tried that?<br><br></div><div>Also, a small example that demonstrates your need would do wonders to help us understand your use case better.<br></div><div> </div></div>-- <br><div class="gmail_signature" data-smartmail="gmail_signature">--Guido van Rossum (<a href="http://python.org/~guido" target="_blank">python.org/~guido</a>)</div>
</div></div>