mirror of
https://github.com/python/cpython.git
synced 2025-12-08 06:10:17 +00:00
bpo-44649: Fix dataclasses(slots=True) with a field with a default, but init=False (GH-29692)
Special handling is needed, because for non-slots dataclasses the instance attributes are not set: reading from a field just references the class's attribute of the same name, which contains the default value. But this doesn't work for classes using __slots__: they don't read the class's attribute. So in that case (and that case only), initialize the instance attribute. Handle this for both normal defaults, and for fields using default_factory.
(cherry picked from commit d3062f672c)
Co-authored-by: Eric V. Smith <ericvsmith@users.noreply.github.com>
This commit is contained in:
parent
9e7a2e4920
commit
10343bd983
3 changed files with 37 additions and 6 deletions
|
|
@ -2880,6 +2880,28 @@ def test_frozen_pickle(self):
|
|||
self.assertIsNot(obj, p)
|
||||
self.assertEqual(obj, p)
|
||||
|
||||
def test_slots_with_default_no_init(self):
|
||||
# Originally reported in bpo-44649.
|
||||
@dataclass(slots=True)
|
||||
class A:
|
||||
a: str
|
||||
b: str = field(default='b', init=False)
|
||||
|
||||
obj = A("a")
|
||||
self.assertEqual(obj.a, 'a')
|
||||
self.assertEqual(obj.b, 'b')
|
||||
|
||||
def test_slots_with_default_factory_no_init(self):
|
||||
# Originally reported in bpo-44649.
|
||||
@dataclass(slots=True)
|
||||
class A:
|
||||
a: str
|
||||
b: str = field(default_factory=lambda:'b', init=False)
|
||||
|
||||
obj = A("a")
|
||||
self.assertEqual(obj.a, 'a')
|
||||
self.assertEqual(obj.b, 'b')
|
||||
|
||||
class TestDescriptors(unittest.TestCase):
|
||||
def test_set_name(self):
|
||||
# See bpo-33141.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue