Skip to content

Commit c1a66bd

Browse files
authored
Remove an unnecessary copy of the 'namespace' parameter to make_dataclass(). (GH-25372)
1 parent 85918e4 commit c1a66bd

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

Lib/dataclasses.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1233,14 +1233,12 @@ class C(Base):
12331233

12341234
if namespace is None:
12351235
namespace = {}
1236-
else:
1237-
# Copy namespace since we're going to mutate it.
1238-
namespace = namespace.copy()
12391236

12401237
# While we're looking through the field names, validate that they
12411238
# are identifiers, are not keywords, and not duplicates.
12421239
seen = set()
1243-
anns = {}
1240+
annotations = {}
1241+
defaults = {}
12441242
for item in fields:
12451243
if isinstance(item, str):
12461244
name = item
@@ -1249,7 +1247,7 @@ class C(Base):
12491247
name, tp, = item
12501248
elif len(item) == 3:
12511249
name, tp, spec = item
1252-
namespace[name] = spec
1250+
defaults[name] = spec
12531251
else:
12541252
raise TypeError(f'Invalid field: {item!r}')
12551253

@@ -1261,12 +1259,19 @@ class C(Base):
12611259
raise TypeError(f'Field name duplicated: {name!r}')
12621260

12631261
seen.add(name)
1264-
anns[name] = tp
1262+
annotations[name] = tp
1263+
1264+
# Update 'ns' with the user-supplied namespace plus our calculated values.
1265+
def exec_body_callback(ns):
1266+
ns.update(namespace)
1267+
ns.update(defaults)
1268+
ns['__annotations__'] = annotations
12651269

1266-
namespace['__annotations__'] = anns
12671270
# We use `types.new_class()` instead of simply `type()` to allow dynamic creation
12681271
# of generic dataclassses.
1269-
cls = types.new_class(cls_name, bases, {}, lambda ns: ns.update(namespace))
1272+
cls = types.new_class(cls_name, bases, {}, exec_body_callback)
1273+
1274+
# Apply the normal decorator.
12701275
return dataclass(cls, init=init, repr=repr, eq=eq, order=order,
12711276
unsafe_hash=unsafe_hash, frozen=frozen,
12721277
match_args=match_args)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Remove an unneeded copy of the namespace passed to
2+
dataclasses.make_dataclass().

0 commit comments

Comments
 (0)