mirror of
https://github.com/python/cpython.git
synced 2025-11-01 02:38:53 +00:00
bpo-42269: Add slots parameter to dataclass decorator (GH-24171)
Add slots parameter to dataclass decorator and make_dataclass function.
This commit is contained in:
parent
558df90109
commit
c24199184b
5 changed files with 111 additions and 11 deletions
|
|
@ -2781,6 +2781,59 @@ class TestSlots(unittest.TestCase):
|
|||
# We can add a new field to the derived instance.
|
||||
d.z = 10
|
||||
|
||||
def test_generated_slots(self):
|
||||
@dataclass(slots=True)
|
||||
class C:
|
||||
x: int
|
||||
y: int
|
||||
|
||||
c = C(1, 2)
|
||||
self.assertEqual((c.x, c.y), (1, 2))
|
||||
|
||||
c.x = 3
|
||||
c.y = 4
|
||||
self.assertEqual((c.x, c.y), (3, 4))
|
||||
|
||||
with self.assertRaisesRegex(AttributeError, "'C' object has no attribute 'z'"):
|
||||
c.z = 5
|
||||
|
||||
def test_add_slots_when_slots_exists(self):
|
||||
with self.assertRaisesRegex(TypeError, '^C already specifies __slots__$'):
|
||||
@dataclass(slots=True)
|
||||
class C:
|
||||
__slots__ = ('x',)
|
||||
x: int
|
||||
|
||||
def test_generated_slots_value(self):
|
||||
@dataclass(slots=True)
|
||||
class Base:
|
||||
x: int
|
||||
|
||||
self.assertEqual(Base.__slots__, ('x',))
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Delivered(Base):
|
||||
y: int
|
||||
|
||||
self.assertEqual(Delivered.__slots__, ('x', 'y'))
|
||||
|
||||
@dataclass
|
||||
class AnotherDelivered(Base):
|
||||
z: int
|
||||
|
||||
self.assertTrue('__slots__' not in AnotherDelivered.__dict__)
|
||||
|
||||
def test_returns_new_class(self):
|
||||
class A:
|
||||
x: int
|
||||
|
||||
B = dataclass(A, slots=True)
|
||||
self.assertIsNot(A, B)
|
||||
|
||||
self.assertFalse(hasattr(A, "__slots__"))
|
||||
self.assertTrue(hasattr(B, "__slots__"))
|
||||
|
||||
|
||||
class TestDescriptors(unittest.TestCase):
|
||||
def test_set_name(self):
|
||||
# See bpo-33141.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue