Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 29f98b4

Browse files
authored
gh-96151: Use a private name for passing builtins to dataclass. This now allows for a field named BUILTIN (gh-98143)
1 parent 87b5fd9 commit 29f98b4

File tree

3 files changed

+13
-5
lines changed

3 files changed

+13
-5
lines changed

Lib/dataclasses.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -426,13 +426,11 @@ def wrapper(self):
426426

427427
def _create_fn(name, args, body, *, globals=None, locals=None,
428428
return_type=MISSING):
429-
# Note that we mutate locals when exec() is called. Caller
430-
# beware! The only callers are internal to this module, so no
429+
# Note that we may mutate locals. Callers beware!
430+
# The only callers are internal to this module, so no
431431
# worries about external callers.
432432
if locals is None:
433433
locals = {}
434-
if 'BUILTINS' not in locals:
435-
locals['BUILTINS'] = builtins
436434
return_annotation = ''
437435
if return_type is not MISSING:
438436
locals['_return_type'] = return_type
@@ -462,7 +460,7 @@ def _field_assign(frozen, name, value, self_name):
462460
# self_name is what "self" is called in this function: don't
463461
# hard-code "self", since that might be a field name.
464462
if frozen:
465-
return f'BUILTINS.object.__setattr__({self_name},{name!r},{value})'
463+
return f'__dataclass_builtins_object__.__setattr__({self_name},{name!r},{value})'
466464
return f'{self_name}.{name}={value}'
467465

468466

@@ -569,6 +567,7 @@ def _init_fn(fields, std_fields, kw_only_fields, frozen, has_post_init,
569567
locals.update({
570568
'MISSING': MISSING,
571569
'_HAS_DEFAULT_FACTORY': _HAS_DEFAULT_FACTORY,
570+
'__dataclass_builtins_object__': object,
572571
})
573572

574573
body_lines = []

Lib/test/test_dataclasses.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,14 @@ class C:
257257
c = C('foo')
258258
self.assertEqual(c.object, 'foo')
259259

260+
def test_field_named_BUILTINS_frozen(self):
261+
# gh-96151
262+
@dataclass(frozen=True)
263+
class C:
264+
BUILTINS: int
265+
c = C(5)
266+
self.assertEqual(c.BUILTINS, 5)
267+
260268
def test_field_named_like_builtin(self):
261269
# Attribute names can shadow built-in names
262270
# since code generation is used.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Allow ``BUILTINS`` to be a valid field name for frozen dataclasses.

0 commit comments

Comments
 (0)