Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -725,25 +725,25 @@ def _init_fn(fields, std_fields, kw_only_fields, frozen, has_post_init,
annotation_fields=annotation_fields)


def _frozen_get_del_attr(cls, fields, func_builder):
locals = {'cls': cls,
def _frozen_set_del_attr(cls, fields, func_builder):
locals = {'__class__': cls,
'FrozenInstanceError': FrozenInstanceError}
condition = 'type(self) is cls'
condition = 'type(self) is __class__'
if fields:
condition += ' or name in {' + ', '.join(repr(f.name) for f in fields) + '}'

func_builder.add_fn('__setattr__',
('self', 'name', 'value'),
(f' if {condition}:',
' raise FrozenInstanceError(f"cannot assign to field {name!r}")',
f' super(cls, self).__setattr__(name, value)'),
f' super(__class__, self).__setattr__(name, value)'),
locals=locals,
overwrite_error=True)
func_builder.add_fn('__delattr__',
('self', 'name'),
(f' if {condition}:',
' raise FrozenInstanceError(f"cannot delete field {name!r}")',
f' super(cls, self).__delattr__(name)'),
f' super(__class__, self).__delattr__(name)'),
locals=locals,
overwrite_error=True)

Expand Down Expand Up @@ -1199,7 +1199,7 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen,
overwrite_error='Consider using functools.total_ordering')

if frozen:
_frozen_get_del_attr(cls, field_list, func_builder)
_frozen_set_del_attr(cls, field_list, func_builder)

# Decide if/how we're going to create a hash function.
hash_action = _hash_action[bool(unsafe_hash),
Expand Down Expand Up @@ -1292,10 +1292,18 @@ def _update_func_cell_for__class__(f, oldcls, newcls):
# This function doesn't reference __class__, so nothing to do.
return False
# Fix the cell to point to the new class, if it's already pointing
# at the old class. I'm not convinced that the "is oldcls" test
# is needed, but other than performance can't hurt.
# at the old class.
closure = f.__closure__[idx]
if closure.cell_contents is oldcls:

try:
contents = closure.cell_contents
except ValueError:
# Cell is empty
return False

# This check makes it so we avoid updating an incorrect cell if the
# class body contains a function that was defined in a different class.
if contents is oldcls:
closure.cell_contents = newcls
return True
return False
Expand Down
170 changes: 119 additions & 51 deletions Lib/test/test_dataclasses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3054,29 +3054,41 @@ class C(base):


class TestFrozen(unittest.TestCase):
# Some tests have a subtest with a slotted dataclass.
# See https://github.com/python/cpython/issues/105936 for the reasons.

def test_frozen(self):
@dataclass(frozen=True)
class C:
i: int
for slots in (False, True):
with self.subTest(slots=slots):

c = C(10)
self.assertEqual(c.i, 10)
with self.assertRaises(FrozenInstanceError):
c.i = 5
self.assertEqual(c.i, 10)
@dataclass(frozen=True, slots=slots)
class C:
i: int

c = C(10)
self.assertEqual(c.i, 10)
with self.assertRaises(FrozenInstanceError):
c.i = 5
self.assertEqual(c.i, 10)
with self.assertRaises(FrozenInstanceError):
del c.i
self.assertEqual(c.i, 10)

def test_frozen_empty(self):
@dataclass(frozen=True)
class C:
pass
for slots in (False, True):
with self.subTest(slots=slots):

c = C()
self.assertNotHasAttr(c, 'i')
with self.assertRaises(FrozenInstanceError):
c.i = 5
self.assertNotHasAttr(c, 'i')
with self.assertRaises(FrozenInstanceError):
del c.i
@dataclass(frozen=True, slots=slots)
class C:
pass

c = C()
self.assertNotHasAttr(c, 'i')
with self.assertRaises(FrozenInstanceError):
c.i = 5
self.assertNotHasAttr(c, 'i')
with self.assertRaises(FrozenInstanceError):
del c.i

def test_inherit(self):
@dataclass(frozen=True)
Expand Down Expand Up @@ -3272,41 +3284,43 @@ class D(I):
d.i = 5

def test_non_frozen_normal_derived(self):
# See bpo-32953.
# See bpo-32953 and https://github.com/python/cpython/issues/105936
for slots in (False, True):
with self.subTest(slots=slots):

@dataclass(frozen=True)
class D:
x: int
y: int = 10
@dataclass(frozen=True, slots=slots)
class D:
x: int
y: int = 10

class S(D):
pass

s = S(3)
self.assertEqual(s.x, 3)
self.assertEqual(s.y, 10)
s.cached = True

# But can't change the frozen attributes.
with self.assertRaises(FrozenInstanceError):
s.x = 5
with self.assertRaises(FrozenInstanceError):
s.y = 5
self.assertEqual(s.x, 3)
self.assertEqual(s.y, 10)
self.assertEqual(s.cached, True)
class S(D):
pass

with self.assertRaises(FrozenInstanceError):
del s.x
self.assertEqual(s.x, 3)
with self.assertRaises(FrozenInstanceError):
del s.y
self.assertEqual(s.y, 10)
del s.cached
self.assertNotHasAttr(s, 'cached')
with self.assertRaises(AttributeError) as cm:
del s.cached
self.assertNotIsInstance(cm.exception, FrozenInstanceError)
s = S(3)
self.assertEqual(s.x, 3)
self.assertEqual(s.y, 10)
s.cached = True

# But can't change the frozen attributes.
with self.assertRaises(FrozenInstanceError):
s.x = 5
with self.assertRaises(FrozenInstanceError):
s.y = 5
self.assertEqual(s.x, 3)
self.assertEqual(s.y, 10)
self.assertEqual(s.cached, True)

with self.assertRaises(FrozenInstanceError):
del s.x
self.assertEqual(s.x, 3)
with self.assertRaises(FrozenInstanceError):
del s.y
self.assertEqual(s.y, 10)
del s.cached
self.assertNotHasAttr(s, 'cached')
with self.assertRaises(AttributeError) as cm:
del s.cached
self.assertNotIsInstance(cm.exception, FrozenInstanceError)

def test_non_frozen_normal_derived_from_empty_frozen(self):
@dataclass(frozen=True)
Expand Down Expand Up @@ -3974,6 +3988,14 @@ class SlotsTest:

return SlotsTest

# See https://github.com/python/cpython/issues/135228#issuecomment-3755979059
def make_frozen():
@dataclass(frozen=True, slots=True)
class SlotsTest:
pass

return SlotsTest

def make_with_annotations():
@dataclass(slots=True)
class SlotsTest:
Expand All @@ -3999,7 +4021,7 @@ class SlotsTest:

return SlotsTest

for make in (make_simple, make_with_annotations, make_with_annotations_and_method, make_with_forwardref):
for make in (make_simple, make_frozen, make_with_annotations, make_with_annotations_and_method, make_with_forwardref):
with self.subTest(make=make):
C = make()
support.gc_collect()
Expand Down Expand Up @@ -5343,5 +5365,51 @@ def cls(self):
# one will be keeping a reference to the underlying class A.
self.assertIs(A().cls(), B)

def test_empty_class_cell(self):
# gh-148947: Make sure that we explicitly handle the empty class cell.
def maker():
if False:
__class__ = 42

def method(self):
return __class__
return method

from dataclasses import dataclass

@dataclass(slots=True)
class X:
a: int

meth = maker()

with self.assertRaisesRegex(NameError, '__class__'):
X(1).meth()

def test_class_cell_from_other_class(self):
# This test fails without the "is oldcls" check in
# _update_func_cell_for__class__.
class Base:
def meth(self):
return "Base"

class Child(Base):
def meth(self):
return super().meth() + " Child"

@dataclass(slots=True)
class DC(Child):
a: int

meth = Child.meth

closure = DC.meth.__closure__
self.assertEqual(len(closure), 1)
self.assertIs(closure[0].cell_contents, Child)

self.assertEqual(DC(1).meth(), "Base Child")



if __name__ == '__main__':
unittest.main()
Loading