diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py index b40559f8493e2857b3b2362a273ee0f47e4b2c33_TGliL2RhdGFjbGFzc2VzLnB5..24e2855ed095e37a5d02ee17a25a806c14a4227c_TGliL2RhdGFjbGFzc2VzLnB5 100644 --- a/Lib/dataclasses.py +++ b/Lib/dataclasses.py @@ -1233,10 +1233,7 @@ 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() @@ -1239,8 +1236,9 @@ # 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 @@ 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,5 +1259,5 @@ raise TypeError(f'Field name duplicated: {name!r}') seen.add(name) - anns[name] = tp + annotations[name] = tp @@ -1265,4 +1263,9 @@ - namespace['__annotations__'] = anns + # 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 + # We use `types.new_class()` instead of simply `type()` to allow dynamic creation # of generic dataclassses. @@ -1267,6 +1270,8 @@ # 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) diff --git a/Misc/NEWS.d/next/Library/2021-04-12-18-01-10.bpo-43820.YkqYW4.rst b/Misc/NEWS.d/next/Library/2021-04-12-18-01-10.bpo-43820.YkqYW4.rst new file mode 100644 index 0000000000000000000000000000000000000000..24e2855ed095e37a5d02ee17a25a806c14a4227c_TWlzYy9ORVdTLmQvbmV4dC9MaWJyYXJ5LzIwMjEtMDQtMTItMTgtMDEtMTAuYnBvLTQzODIwLllrcVlXNC5yc3Q= --- /dev/null +++ b/Misc/NEWS.d/next/Library/2021-04-12-18-01-10.bpo-43820.YkqYW4.rst @@ -0,0 +1,2 @@ +Remove an unneeded copy of the namespace passed to +dataclasses.make_dataclass().