On 12/11/2019 1:23 PM, Andrew Barnert via Python-ideas wrote:
On Dec 11, 2019, at 08:56, Arthur Pastel <[email protected]> wrote:
When creating frozen dataclasses, attribute initialization must be done using
`object.__setattr__()` it would be nice to allow attribute assignment in the
`__init__` and `__post_init__`.
But how would you implement that?
Frozen means that attribute assignment isn’t allowed. The __post_init__ method
isn’t magic, it’s just a normal method that gets called normally by the
generated __init__. What you’re proposing is that we should make it magic.
Which would be useful, but you need to come up with magic that works.
If dataclass handled freezeable types (the objects are mutable until you call
freeze, after which they’re not), this would be easy (frozen now just means
freezable, plus freeze is called by the generated __init__ right after the
__post_init__). But it doesn’t, because freezing is complicated.
So, what else could you do? Make __setattr__ check the stack and see if it’s
being called from type(self).__post_init__? Add an extra hidden attribute to
every instance just to track whether you’re inside __post_init__ so __setattr__
can check it?
I agree with Andrew: it's a great idea, but I couldn't come up with a
way to implement it, so I followed attrs lead instead. Maybe someone can
come up with a good way to implement it: does attrs still do the same
object.__setattr__ trick?
Eric
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/NDXGJQISQA6ER3UVPR6UOY2CJPQVSBGE/
Code of Conduct: http://python.org/psf/codeofconduct/