Skip to content

Commit e4275f4

Browse files
authored
gh-107838: In dataclasses, improve error message when a non-default field follows a default field. (gh-107842)
Add the name of the previous default argument field in an error message.
1 parent 37d8b90 commit e4275f4

File tree

2 files changed

+7
-7
lines changed

2 files changed

+7
-7
lines changed

Lib/dataclasses.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -575,15 +575,15 @@ def _init_fn(fields, std_fields, kw_only_fields, frozen, has_post_init,
575575
# message, and future-proofs us in case we build up the function
576576
# using ast.
577577

578-
seen_default = False
578+
seen_default = None
579579
for f in std_fields:
580580
# Only consider the non-kw-only fields in the __init__ call.
581581
if f.init:
582582
if not (f.default is MISSING and f.default_factory is MISSING):
583-
seen_default = True
583+
seen_default = f
584584
elif seen_default:
585585
raise TypeError(f'non-default argument {f.name!r} '
586-
'follows default argument')
586+
f'follows default argument {seen_default.name!r}')
587587

588588
locals = {f'__dataclass_type_{f.name}__': f.type for f in fields}
589589
locals.update({

Lib/test/test_dataclasses.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ class C:
134134
# Non-defaults following defaults.
135135
with self.assertRaisesRegex(TypeError,
136136
"non-default argument 'y' follows "
137-
"default argument"):
137+
"default argument 'x'"):
138138
@dataclass
139139
class C:
140140
x: int = 0
@@ -143,7 +143,7 @@ class C:
143143
# A derived class adds a non-default field after a default one.
144144
with self.assertRaisesRegex(TypeError,
145145
"non-default argument 'y' follows "
146-
"default argument"):
146+
"default argument 'x'"):
147147
@dataclass
148148
class B:
149149
x: int = 0
@@ -156,7 +156,7 @@ class C(B):
156156
# a field which didn't use to have a default.
157157
with self.assertRaisesRegex(TypeError,
158158
"non-default argument 'y' follows "
159-
"default argument"):
159+
"default argument 'x'"):
160160
@dataclass
161161
class B:
162162
x: int
@@ -4521,7 +4521,7 @@ class A:
45214521

45224522
# Make sure we still check for non-kwarg non-defaults not following
45234523
# defaults.
4524-
err_regex = "non-default argument 'z' follows default argument"
4524+
err_regex = "non-default argument 'z' follows default argument 'a'"
45254525
with self.assertRaisesRegex(TypeError, err_regex):
45264526
@dataclass
45274527
class A:

0 commit comments

Comments
 (0)