Skip to content

Commit 83f564f

Browse files
Clean up and enhance frozen dataclass tests. (GH-6380)
* Add a test for frozen with unhashable field value. * Improve a comment. (cherry picked from commit 7494091) Co-authored-by: Eric V. Smith <[email protected]>
1 parent 04eac02 commit 83f564f

File tree

1 file changed

+38
-27
lines changed

1 file changed

+38
-27
lines changed

Lib/test/test_dataclasses.py

Lines changed: 38 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -2191,33 +2191,6 @@ def __repr__(self):
21912191
self.assertEqual(repr(C(0)), 'x')
21922192

21932193

2194-
class TestFrozen(unittest.TestCase):
2195-
def test_overwriting_frozen(self):
2196-
# frozen uses __setattr__ and __delattr__.
2197-
with self.assertRaisesRegex(TypeError,
2198-
'Cannot overwrite attribute __setattr__'):
2199-
@dataclass(frozen=True)
2200-
class C:
2201-
x: int
2202-
def __setattr__(self):
2203-
pass
2204-
2205-
with self.assertRaisesRegex(TypeError,
2206-
'Cannot overwrite attribute __delattr__'):
2207-
@dataclass(frozen=True)
2208-
class C:
2209-
x: int
2210-
def __delattr__(self):
2211-
pass
2212-
2213-
@dataclass(frozen=False)
2214-
class C:
2215-
x: int
2216-
def __setattr__(self, name, value):
2217-
self.__dict__['x'] = value * 2
2218-
self.assertEqual(C(10).x, 20)
2219-
2220-
22212194
class TestEq(unittest.TestCase):
22222195
def test_no_eq(self):
22232196
# Test a class with no __eq__ and eq=False.
@@ -2672,6 +2645,44 @@ class S(D):
26722645
self.assertEqual(s.y, 10)
26732646
self.assertEqual(s.cached, True)
26742647

2648+
def test_overwriting_frozen(self):
2649+
# frozen uses __setattr__ and __delattr__.
2650+
with self.assertRaisesRegex(TypeError,
2651+
'Cannot overwrite attribute __setattr__'):
2652+
@dataclass(frozen=True)
2653+
class C:
2654+
x: int
2655+
def __setattr__(self):
2656+
pass
2657+
2658+
with self.assertRaisesRegex(TypeError,
2659+
'Cannot overwrite attribute __delattr__'):
2660+
@dataclass(frozen=True)
2661+
class C:
2662+
x: int
2663+
def __delattr__(self):
2664+
pass
2665+
2666+
@dataclass(frozen=False)
2667+
class C:
2668+
x: int
2669+
def __setattr__(self, name, value):
2670+
self.__dict__['x'] = value * 2
2671+
self.assertEqual(C(10).x, 20)
2672+
2673+
def test_frozen_hash(self):
2674+
@dataclass(frozen=True)
2675+
class C:
2676+
x: Any
2677+
2678+
# If x is immutable, we can compute the hash. No exception is
2679+
# raised.
2680+
hash(C(3))
2681+
2682+
# If x is mutable, computing the hash is an error.
2683+
with self.assertRaisesRegex(TypeError, 'unhashable type'):
2684+
hash(C({}))
2685+
26752686

26762687
class TestSlots(unittest.TestCase):
26772688
def test_simple(self):

0 commit comments

Comments
 (0)