summaryrefslogtreecommitdiffstats
path: root/Lib/dataclasses.py
diff options
context:
space:
mode:
authorEric V. Smith <ericvsmith@users.noreply.github.com>2021-04-13 01:02:02 (GMT)
committerGitHub <noreply@github.com>2021-04-13 01:02:02 (GMT)
commitc1a66bdd6f884e2ec813891c5c7e2b1ceeede8f1 (patch)
treea39ea5c10bbf28ca900ca49709d3a5c14e057507 /Lib/dataclasses.py
parent85918e4ab6e9410008aef6dedf000d24b3e120ea (diff)
downloadcpython-c1a66bdd6f884e2ec813891c5c7e2b1ceeede8f1.zip
cpython-c1a66bdd6f884e2ec813891c5c7e2b1ceeede8f1.tar.gz
cpython-c1a66bdd6f884e2ec813891c5c7e2b1ceeede8f1.tar.bz2
Remove an unnecessary copy of the 'namespace' parameter to make_dataclass(). (GH-25372)
Diffstat (limited to 'Lib/dataclasses.py')
-rw-r--r--Lib/dataclasses.py21
1 files changed, 13 insertions, 8 deletions
diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py
index e8eb206..3ccfbbd 100644
--- a/Lib/dataclasses.py
+++ b/Lib/dataclasses.py
@@ -1233,14 +1233,12 @@ def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,
if namespace is None:
namespace = {}
- else:
- # Copy namespace since we're going to mutate it.
- namespace = namespace.copy()
# While we're looking through the field names, validate that they
# are identifiers, are not keywords, and not duplicates.
seen = set()
- anns = {}
+ annotations = {}
+ defaults = {}
for item in fields:
if isinstance(item, str):
name = item
@@ -1249,7 +1247,7 @@ def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,
name, tp, = item
elif len(item) == 3:
name, tp, spec = item
- namespace[name] = spec
+ defaults[name] = spec
else:
raise TypeError(f'Invalid field: {item!r}')
@@ -1261,12 +1259,19 @@ def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,
raise TypeError(f'Field name duplicated: {name!r}')
seen.add(name)
- anns[name] = tp
+ annotations[name] = tp
+
+ # Update 'ns' with the user-supplied namespace plus our calculated values.
+ def exec_body_callback(ns):
+ ns.update(namespace)
+ ns.update(defaults)
+ ns['__annotations__'] = annotations
- namespace['__annotations__'] = anns
# We use `types.new_class()` instead of simply `type()` to allow dynamic creation
# of generic dataclassses.
- cls = types.new_class(cls_name, bases, {}, lambda ns: ns.update(namespace))
+ cls = types.new_class(cls_name, bases, {}, exec_body_callback)
+
+ # Apply the normal decorator.
return dataclass(cls, init=init, repr=repr, eq=eq, order=order,
unsafe_hash=unsafe_hash, frozen=frozen,
match_args=match_args)