diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py index 035678d902adaf9..b45e09cbf1d22d5 100644 --- a/Lib/dataclasses.py +++ b/Lib/dataclasses.py @@ -1142,7 +1142,7 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen, func_builder = _FuncBuilder(globals) - if init: + if init and '__init__' not in cls.__dict__: # Does this class have a post-init function? has_post_init = hasattr(cls, _POST_INIT_NAME) diff --git a/Lib/test/test_dataclasses/__init__.py b/Lib/test/test_dataclasses/__init__.py index 2468e3e64dd621c..c464b145adbaed8 100644 --- a/Lib/test/test_dataclasses/__init__.py +++ b/Lib/test/test_dataclasses/__init__.py @@ -2502,6 +2502,26 @@ def __init__(self, x): self.x = 2 * x self.assertEqual(C(5).x, 10) + def test_overwriting_init_with_field_ordering_conflict(self): + # gh-148941: When a class defines its own __init__, @dataclass must + # not raise TypeError due to field ordering issues in the generated + # __init__ signature — it would be discarded anyway. + @dataclass + class Base: + x: int = 0 # has a default + + # Without a user-defined __init__, this would raise TypeError + # ("non-default argument 'y' follows default argument 'x'"). + @dataclass + class Child(Base): + y: int # no default — would produce invalid signature + def __init__(self, y): + self.y = y + + self.assertEqual(Child(5).y, 5) + # Verify it's Child's own __init__, not a generated one. + self.assertNotIn('x', vars(Child(5))) + def test_inherit_from_protocol(self): # Dataclasses inheriting from protocol should preserve their own `__init__`. # See bpo-45081. diff --git a/Misc/NEWS.d/next/Library/2026-06-09-16-41-45.gh-issue-148941.aB3kLm.rst b/Misc/NEWS.d/next/Library/2026-06-09-16-41-45.gh-issue-148941.aB3kLm.rst new file mode 100644 index 000000000000000..37648b7ca979f78 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-06-09-16-41-45.gh-issue-148941.aB3kLm.rst @@ -0,0 +1,3 @@ +Fix :func:`dataclasses.dataclass` raising :exc:`TypeError` about field +ordering when a subclass defines its own :meth:`~object.__init__` and +inherits from a dataclass that has fields with default values.