Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
20 changes: 20 additions & 0 deletions Lib/test/test_dataclasses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Loading