Hello

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.

There are two workarounds without changing the base class to frozen=False,
which could be in a library.

1. Use object.__setattr__, this is ugly and not very user or beginner
friendly.
2. Extract __post_init__ out into a factory function. Then it also loses
all the advantages of the __post_init__ and InitVar mechanism.

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 __post_init__ function.

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.

Thanks
Ben Lewis
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to