[issue46757] dataclasses should define an empty __post_init__

Raymond Hettinger report at bugs.python.org
Sun Feb 20 21:00:28 EST 2022


Raymond Hettinger <raymond.hettinger at gmail.com> added the comment:

-1

* I concur with Eric that this is mostly not needed.  Probably 99.95% of dataclass use case don't need this.  When it is needed, it is trivial to implement and probably should be explicit rather that implicit.

* Vedran is also correct in noting that it would sometimes mask errors.

* There is a runtime cost for all dataclasses that do not use __post_init__.  Calling an empty method takes time.  We shouldn't make all users pay for a feature that almost no one needs.

* With respect to use of super(), it might help a little bit, but only because __post_init__() takes no arguments.  For the other methods in cooperative multiple inheritance, a user would need to either incorporate a straight forward hasattr() check or add a terminal root class as described in super-considered-super.  I see no reason to make __post_init__ a special case that would differ from other methods (for example, object() doesn't provide an empty __call__ or __getitem__).

* Adding a default __post_init__ will create a new problem.  Currently, it is possible to easily introspect and determine whether a __post_init__ has been provided, but if there is an empty default, it becomes a much more tricky test.  We had this problem with functools.total_ordering.  When that tool was first created, we could easily use hasattr() to test for a user defined rich comparison method.  But after default methods were added to object(), the test because much more delicate:  ``getattr(cls, op, None) is not getattr(object, op, None)``.  Likewise the Hashable ABC cannot just use hasattr() because __hash__() is always present and has to be set to None to turn it off.  A default __post_init__ is worse than both cases.  You can't test for it, so you just have to call it, not knowing in advance whether it would do anything.

* Anyone supporting multiple versions of Python will still need to write the hasattr() check or provide a terminal/root class.  They won't be able to rely on the default being present.

I recommend leaving dataclasses as is.

----------
nosy: +rhettinger

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue46757>
_______________________________________


More information about the Python-bugs-list mailing list