Skip to content
Closed
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Merge branch 'main' into dataclass-slots
  • Loading branch information
AlexWaygood authored May 3, 2022
commit 3d04919ab239c0a9bd0ce767554e1e1dc29b9265
71 changes: 71 additions & 0 deletions Lib/test/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -3096,6 +3096,77 @@ class NonDataclassSubclassOfPointWithNoSlots(Point): pass
# subclass does not define __slots__ and is not frozen.
n.z = 5

def test_slots_no_weakref(self):
@dataclass(slots=True)
class A:
# No weakref.
pass

self.assertNotIn("__weakref__", A.__slots__)
a = A()
with self.assertRaisesRegex(TypeError,
"cannot create weak reference"):
weakref.ref(a)

def test_slots_weakref(self):
@dataclass(slots=True, weakref_slot=True)
class A:
a: int

self.assertIn("__weakref__", A.__slots__)
a = A(1)
weakref.ref(a)

def test_slots_weakref_base_str(self):
class Base:
__slots__ = '__weakref__'

@dataclass(slots=True)
class A(Base):
a: int

# __weakref__ is in the base class, not A. But an A is still weakref-able.
self.assertIn("__weakref__", Base.__slots__)
self.assertNotIn("__weakref__", A.__slots__)
a = A(1)
weakref.ref(a)

def test_slots_weakref_base_tuple(self):
# Same as test_slots_weakref_base, but use a tuple instead of a string
# in the base class.
class Base:
__slots__ = ('__weakref__',)

@dataclass(slots=True)
class A(Base):
a: int

# __weakref__ is in the base class, not A. But an A is still
# weakref-able.
self.assertIn("__weakref__", Base.__slots__)
self.assertNotIn("__weakref__", A.__slots__)
a = A(1)
weakref.ref(a)

def test_weakref_slot_without_slot(self):
with self.assertRaisesRegex(TypeError,
"weakref_slot is True but slots is False"):
@dataclass(weakref_slot=True)
class A:
a: int

def test_weakref_slot_make_dataclass(self):
A = make_dataclass('A', [('a', int),], slots=True, weakref_slot=True)
self.assertIn("__weakref__", A.__slots__)
a = A(1)
weakref.ref(a)

# And make sure if raises if slots=True is not given.
with self.assertRaisesRegex(TypeError,
"weakref_slot is True but slots is False"):
B = make_dataclass('B', [('a', int),], weakref_slot=True)


class TestDescriptors(unittest.TestCase):
def test_set_name(self):
# See bpo-33141.
Expand Down
You are viewing a condensed version of this merge commit. You can view the full changes here.