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

Skip to content

Commit ca24e49

Browse files
[3.11] gh-96151: Use a private name for passing builtins to dataclass. This now allows for a field named BUILTIN (gh-98143) (gh-98900)
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 57dd110 commit ca24e49

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

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

450448

@@ -551,6 +549,7 @@ def _init_fn(fields, std_fields, kw_only_fields, frozen, has_post_init,
551549
locals.update({
552550
'MISSING': MISSING,
553551
'_HAS_DEFAULT_FACTORY': _HAS_DEFAULT_FACTORY,
552+
'__dataclass_builtins_object__': object,
554553
})
555554

556555
body_lines = []

Lib/test/test_dataclasses.py

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

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