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

Skip to content

Commit 789d132

Browse files
[3.10] gh-96151: Use a private name for passing builtins to dataclass. This now allows for a field named BUILTIN (gh-98143) (gh-98899)
gh-96151: Use a private name for passing builtins to dataclass. This now allows for a field named BUILTIN (gh-98143) (cherry picked from commit 29f98b4) Co-authored-by: Shantanu <[email protected]> Co-authored-by: Shantanu <[email protected]>
1 parent 23545fb commit 789d132

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
@@ -411,13 +411,11 @@ def wrapper(self):
411411

412412
def _create_fn(name, args, body, *, globals=None, locals=None,
413413
return_type=MISSING):
414-
# Note that we mutate locals when exec() is called. Caller
415-
# beware! The only callers are internal to this module, so no
414+
# Note that we may mutate locals. Callers beware!
415+
# The only callers are internal to this module, so no
416416
# worries about external callers.
417417
if locals is None:
418418
locals = {}
419-
if 'BUILTINS' not in locals:
420-
locals['BUILTINS'] = builtins
421419
return_annotation = ''
422420
if return_type is not MISSING:
423421
locals['_return_type'] = return_type
@@ -443,7 +441,7 @@ def _field_assign(frozen, name, value, self_name):
443441
# self_name is what "self" is called in this function: don't
444442
# hard-code "self", since that might be a field name.
445443
if frozen:
446-
return f'BUILTINS.object.__setattr__({self_name},{name!r},{value})'
444+
return f'__dataclass_builtins_object__.__setattr__({self_name},{name!r},{value})'
447445
return f'{self_name}.{name}={value}'
448446

449447

@@ -550,6 +548,7 @@ def _init_fn(fields, std_fields, kw_only_fields, frozen, has_post_init,
550548
locals.update({
551549
'MISSING': MISSING,
552550
'_HAS_DEFAULT_FACTORY': _HAS_DEFAULT_FACTORY,
551+
'__dataclass_builtins_object__': object,
553552
})
554553

555554
body_lines = []

Lib/test/test_dataclasses.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,14 @@ class C:
230230
c = C('foo')
231231
self.assertEqual(c.object, 'foo')
232232

233+
def test_field_named_BUILTINS_frozen(self):
234+
# gh-96151
235+
@dataclass(frozen=True)
236+
class C:
237+
BUILTINS: int
238+
c = C(5)
239+
self.assertEqual(c.BUILTINS, 5)
240+
233241
def test_field_named_like_builtin(self):
234242
# Attribute names can shadow built-in names
235243
# 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)