Debian Codegraph @

Lib/test/test_dataclasses/__init__.py

raw
1 # Deliberately use "from dataclasses import *". Every name in __all__
2 # is tested, so they all must be present. This is a way to catch
3 # missing ones.
4
5 from dataclasses import *
6
7 import abc
8 import annotationlib
9 import io
10 import pickle
11 import inspect
12 import builtins
13 import types
14 import weakref
15 import traceback
16 import sys
17 import textwrap
18 import unittest
19 from unittest.mock import Mock
20 from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict
21 from typing import get_type_hints
22 from collections import deque, OrderedDict, namedtuple, defaultdict
23 from copy import deepcopy
24 from functools import total_ordering, wraps
25
26 import typing # Needed for the string "typing.ClassVar[int]" to work as an annotation.
27 import dataclasses # Needed for the string "dataclasses.InitVar[int]" to work as an annotation.
28
29 from test import support
30 from test.support import import_helper
31
32 # Just any custom exception we can catch.
33 class CustomError(Exception): pass
34
35 class TestCase(unittest.TestCase):
36 def test_no_fields(self):
37 @dataclass
38 class C:
39 pass
40
41 o = C()
42 self.assertEqual(len(fields(C)), 0)
43
44 def test_no_fields_but_member_variable(self):
45 @dataclass
46 class C:
47 i = 0
48
49 o = C()
50 self.assertEqual(len(fields(C)), 0)
51
52 def test_one_field_no_default(self):
53 @dataclass
54 class C:
55 x: int
56
57 o = C(42)
58 self.assertEqual(o.x, 42)
59
60 def test_field_default_default_factory_error(self):
61 msg = "cannot specify both default and default_factory"
62 with self.assertRaisesRegex(ValueError, msg):
63 @dataclass
64 class C:
65 x: int = field(default=1, default_factory=int)
66
67 def test_field_repr(self):
68 int_field = field(default=1, init=True, repr=False, doc='Docstring')
69 int_field.name = "id"
70 repr_output = repr(int_field)
71 expected_output = "Field(name='id',type=None," \
72 f"default=1,default_factory={MISSING!r}," \
73 "init=True,repr=False,hash=None," \
74 "compare=True,metadata=mappingproxy({})," \
75 f"kw_only={MISSING!r}," \
76 "doc='Docstring'," \
77 "_field_type=None)"
78
79 self.assertEqual(repr_output, expected_output)
80
81 def test_field_recursive_repr(self):
82 rec_field = field()
83 rec_field.type = rec_field
84 rec_field.name = "id"
85 repr_output = repr(rec_field)
86
87 self.assertIn(",type=...,", repr_output)
88
89 def test_recursive_annotation(self):
90 class C:
91 pass
92
93 @dataclass
94 class D:
95 C: C = field()
96
97 self.assertIn(",type=...,", repr(D.__dataclass_fields__["C"]))
98
99 def test_dataclass_params_repr(self):
100 # Even though this is testing an internal implementation detail,
101 # it's testing a feature we want to make sure is correctly implemented
102 # for the sake of dataclasses itself
103 @dataclass(slots=True, frozen=True)
104 class Some: pass
105
106 repr_output = repr(Some.__dataclass_params__)
107 expected_output = "_DataclassParams(init=True,repr=True," \
108 "eq=True,order=False,unsafe_hash=False,frozen=True," \
109 "match_args=True,kw_only=False," \
110 "slots=True,weakref_slot=False)"
111 self.assertEqual(repr_output, expected_output)
112
113 def test_dataclass_params_signature(self):
114 # Even though this is testing an internal implementation detail,
115 # it's testing a feature we want to make sure is correctly implemented
116 # for the sake of dataclasses itself
117 @dataclass
118 class Some: pass
119
120 for param in inspect.signature(dataclass).parameters:
121 if param == 'cls':
122 continue
123 self.assertHasAttr(Some.__dataclass_params__, param)
124
125 def test_named_init_params(self):
126 @dataclass
127 class C:
128 x: int
129
130 o = C(x=32)
131 self.assertEqual(o.x, 32)
132
133 def test_two_fields_one_default(self):
134 @dataclass
135 class C:
136 x: int
137 y: int = 0
138
139 o = C(3)
140 self.assertEqual((o.x, o.y), (3, 0))
141
142 # Non-defaults following defaults.
143 with self.assertRaisesRegex(TypeError,
144 "non-default argument 'y' follows "
145 "default argument 'x'"):
146 @dataclass
147 class C:
148 x: int = 0
149 y: int
150
151 # A derived class adds a non-default field after a default one.
152 with self.assertRaisesRegex(TypeError,
153 "non-default argument 'y' follows "
154 "default argument 'x'"):
155 @dataclass
156 class B:
157 x: int = 0
158
159 @dataclass
160 class C(B):
161 y: int
162
163 # Override a base class field and add a default to
164 # a field which didn't use to have a default.
165 with self.assertRaisesRegex(TypeError,
166 "non-default argument 'y' follows "
167 "default argument 'x'"):
168 @dataclass
169 class B:
170 x: int
171 y: int
172
173 @dataclass
174 class C(B):
175 x: int = 0
176
177 def test_overwrite_hash(self):
178 # Test that declaring this class isn't an error. It should
179 # use the user-provided __hash__.
180 @dataclass(frozen=True)
181 class C:
182 x: int
183 def __hash__(self):
184 return 301
185 self.assertEqual(hash(C(100)), 301)
186
187 # Test that declaring this class isn't an error. It should
188 # use the generated __hash__.
189 @dataclass(frozen=True)
190 class C:
191 x: int
192 def __eq__(self, other):
193 return False
194 self.assertEqual(hash(C(100)), hash((100,)))
195
196 # But this one should generate an exception, because with
197 # unsafe_hash=True, it's an error to have a __hash__ defined.
198 with self.assertRaisesRegex(TypeError,
199 'Cannot overwrite attribute __hash__'):
200 @dataclass(unsafe_hash=True)
201 class C:
202 def __hash__(self):
203 pass
204
205 # Creating this class should not generate an exception,
206 # because even though __hash__ exists before @dataclass is
207 # called, (due to __eq__ being defined), since it's None
208 # that's okay.
209 @dataclass(unsafe_hash=True)
210 class C:
211 x: int
212 def __eq__(self):
213 pass
214 # The generated hash function works as we'd expect.
215 self.assertEqual(hash(C(10)), hash((10,)))
216
217 # Creating this class should generate an exception, because
218 # __hash__ exists and is not None, which it would be if it
219 # had been auto-generated due to __eq__ being defined.
220 with self.assertRaisesRegex(TypeError,
221 'Cannot overwrite attribute __hash__'):
222 @dataclass(unsafe_hash=True)
223 class C:
224 x: int
225 def __eq__(self):
226 pass
227 def __hash__(self):
228 pass
229
230 def test_overwrite_fields_in_derived_class(self):
231 # Note that x from C1 replaces x in Base, but the order remains
232 # the same as defined in Base.
233 @dataclass
234 class Base:
235 x: Any = 15.0
236 y: int = 0
237
238 @dataclass
239 class C1(Base):
240 z: int = 10
241 x: int = 15
242
243 o = Base()
244 self.assertEqual(repr(o), 'TestCase.test_overwrite_fields_in_derived_class.<locals>.Base(x=15.0, y=0)')
245
246 o = C1()
247 self.assertEqual(repr(o), 'TestCase.test_overwrite_fields_in_derived_class.<locals>.C1(x=15, y=0, z=10)')
248
249 o = C1(x=5)
250 self.assertEqual(repr(o), 'TestCase.test_overwrite_fields_in_derived_class.<locals>.C1(x=5, y=0, z=10)')
251
252 def test_field_named_self(self):
253 @dataclass
254 class C:
255 self: str
256 c=C('foo')
257 self.assertEqual(c.self, 'foo')
258
259 # Make sure the first parameter is not named 'self'.
260 sig = inspect.signature(C.__init__)
261 first = next(iter(sig.parameters))
262 self.assertNotEqual('self', first)
263
264 # But we do use 'self' if no field named self.
265 @dataclass
266 class C:
267 selfx: str
268
269 # Make sure the first parameter is named 'self'.
270 sig = inspect.signature(C.__init__)
271 first = next(iter(sig.parameters))
272 self.assertEqual('self', first)
273
274 def test_field_named_object(self):
275 @dataclass
276 class C:
277 object: str
278 c = C('foo')
279 self.assertEqual(c.object, 'foo')
280
281 def test_field_named_object_frozen(self):
282 @dataclass(frozen=True)
283 class C:
284 object: str
285 c = C('foo')
286 self.assertEqual(c.object, 'foo')
287
288 def test_field_named_BUILTINS_frozen(self):
289 # gh-96151
290 @dataclass(frozen=True)
291 class C:
292 BUILTINS: int
293 c = C(5)
294 self.assertEqual(c.BUILTINS, 5)
295
296 def test_field_with_special_single_underscore_names(self):
297 # gh-98886
298
299 @dataclass
300 class X:
301 x: int = field(default_factory=lambda: 111)
302 _dflt_x: int = field(default_factory=lambda: 222)
303
304 X()
305
306 @dataclass
307 class Y:
308 y: int = field(default_factory=lambda: 111)
309 _HAS_DEFAULT_FACTORY: int = 222
310
311 assert Y(y=222).y == 222
312
313 def test_field_named_like_builtin(self):
314 # Attribute names can shadow built-in names
315 # since code generation is used.
316 # Ensure that this is not happening.
317 exclusions = {'None', 'True', 'False'}
318 builtins_names = sorted(
319 b for b in builtins.__dict__.keys()
320 if not b.startswith('__') and b not in exclusions
321 )
322 attributes = [(name, str) for name in builtins_names]
323 C = make_dataclass('C', attributes)
324
325 c = C(*[name for name in builtins_names])
326
327 for name in builtins_names:
328 self.assertEqual(getattr(c, name), name)
329
330 def test_field_named_like_builtin_frozen(self):
331 # Attribute names can shadow built-in names
332 # since code generation is used.
333 # Ensure that this is not happening
334 # for frozen data classes.
335 exclusions = {'None', 'True', 'False'}
336 builtins_names = sorted(
337 b for b in builtins.__dict__.keys()
338 if not b.startswith('__') and b not in exclusions
339 )
340 attributes = [(name, str) for name in builtins_names]
341 C = make_dataclass('C', attributes, frozen=True)
342
343 c = C(*[name for name in builtins_names])
344
345 for name in builtins_names:
346 self.assertEqual(getattr(c, name), name)
347
348 def test_0_field_compare(self):
349 # Ensure that order=False is the default.
350 @dataclass
351 class C0:
352 pass
353
354 @dataclass(order=False)
355 class C1:
356 pass
357
358 for cls in [C0, C1]:
359 with self.subTest(cls=cls):
360 self.assertEqual(cls(), cls())
361 for idx, fn in enumerate([lambda a, b: a < b,
362 lambda a, b: a <= b,
363 lambda a, b: a > b,
364 lambda a, b: a >= b]):
365 with self.subTest(idx=idx):
366 with self.assertRaisesRegex(TypeError,
367 f"not supported between instances of '{cls.__name__}' and '{cls.__name__}'"):
368 fn(cls(), cls())
369
370 @dataclass(order=True)
371 class C:
372 pass
373 self.assertLessEqual(C(), C())
374 self.assertGreaterEqual(C(), C())
375
376 def test_1_field_compare(self):
377 # Ensure that order=False is the default.
378 @dataclass
379 class C0:
380 x: int
381
382 @dataclass(order=False)
383 class C1:
384 x: int
385
386 for cls in [C0, C1]:
387 with self.subTest(cls=cls):
388 self.assertEqual(cls(1), cls(1))
389 self.assertNotEqual(cls(0), cls(1))
390 for idx, fn in enumerate([lambda a, b: a < b,
391 lambda a, b: a <= b,
392 lambda a, b: a > b,
393 lambda a, b: a >= b]):
394 with self.subTest(idx=idx):
395 with self.assertRaisesRegex(TypeError,
396 f"not supported between instances of '{cls.__name__}' and '{cls.__name__}'"):
397 fn(cls(0), cls(0))
398
399 @dataclass(order=True)
400 class C:
401 x: int
402 self.assertLess(C(0), C(1))
403 self.assertLessEqual(C(0), C(1))
404 self.assertLessEqual(C(1), C(1))
405 self.assertGreater(C(1), C(0))
406 self.assertGreaterEqual(C(1), C(0))
407 self.assertGreaterEqual(C(1), C(1))
408
409 def test_simple_compare(self):
410 # Ensure that order=False is the default.
411 @dataclass
412 class C0:
413 x: int
414 y: int
415
416 @dataclass(order=False)
417 class C1:
418 x: int
419 y: int
420
421 for cls in [C0, C1]:
422 with self.subTest(cls=cls):
423 self.assertEqual(cls(0, 0), cls(0, 0))
424 self.assertEqual(cls(1, 2), cls(1, 2))
425 self.assertNotEqual(cls(1, 0), cls(0, 0))
426 self.assertNotEqual(cls(1, 0), cls(1, 1))
427 for idx, fn in enumerate([lambda a, b: a < b,
428 lambda a, b: a <= b,
429 lambda a, b: a > b,
430 lambda a, b: a >= b]):
431 with self.subTest(idx=idx):
432 with self.assertRaisesRegex(TypeError,
433 f"not supported between instances of '{cls.__name__}' and '{cls.__name__}'"):
434 fn(cls(0, 0), cls(0, 0))
435
436 @dataclass(order=True)
437 class C:
438 x: int
439 y: int
440
441 for idx, fn in enumerate([lambda a, b: a == b,
442 lambda a, b: a <= b,
443 lambda a, b: a >= b]):
444 with self.subTest(idx=idx):
445 self.assertTrue(fn(C(0, 0), C(0, 0)))
446
447 for idx, fn in enumerate([lambda a, b: a < b,
448 lambda a, b: a <= b,
449 lambda a, b: a != b]):
450 with self.subTest(idx=idx):
451 self.assertTrue(fn(C(0, 0), C(0, 1)))
452 self.assertTrue(fn(C(0, 1), C(1, 0)))
453 self.assertTrue(fn(C(1, 0), C(1, 1)))
454
455 for idx, fn in enumerate([lambda a, b: a > b,
456 lambda a, b: a >= b,
457 lambda a, b: a != b]):
458 with self.subTest(idx=idx):
459 self.assertTrue(fn(C(0, 1), C(0, 0)))
460 self.assertTrue(fn(C(1, 0), C(0, 1)))
461 self.assertTrue(fn(C(1, 1), C(1, 0)))
462
463 def test_compare_subclasses(self):
464 # Comparisons fail for subclasses, even if no fields
465 # are added.
466 @dataclass
467 class B:
468 i: int
469
470 @dataclass
471 class C(B):
472 pass
473
474 for idx, (fn, expected) in enumerate([(lambda a, b: a == b, False),
475 (lambda a, b: a != b, True)]):
476 with self.subTest(idx=idx):
477 self.assertEqual(fn(B(0), C(0)), expected)
478
479 for idx, fn in enumerate([lambda a, b: a < b,
480 lambda a, b: a <= b,
481 lambda a, b: a > b,
482 lambda a, b: a >= b]):
483 with self.subTest(idx=idx):
484 with self.assertRaisesRegex(TypeError,
485 "not supported between instances of 'B' and 'C'"):
486 fn(B(0), C(0))
487
488 def test_eq_order(self):
489 # Test combining eq and order.
490 for (eq, order, result ) in [
491 (False, False, 'neither'),
492 (False, True, 'exception'),
493 (True, False, 'eq_only'),
494 (True, True, 'both'),
495 ]:
496 with self.subTest(eq=eq, order=order):
497 if result == 'exception':
498 with self.assertRaisesRegex(ValueError, 'eq must be true if order is true'):
499 @dataclass(eq=eq, order=order)
500 class C:
501 pass
502 else:
503 @dataclass(eq=eq, order=order)
504 class C:
505 pass
506
507 if result == 'neither':
508 self.assertNotIn('__eq__', C.__dict__)
509 self.assertNotIn('__lt__', C.__dict__)
510 self.assertNotIn('__le__', C.__dict__)
511 self.assertNotIn('__gt__', C.__dict__)
512 self.assertNotIn('__ge__', C.__dict__)
513 elif result == 'both':
514 self.assertIn('__eq__', C.__dict__)
515 self.assertIn('__lt__', C.__dict__)
516 self.assertIn('__le__', C.__dict__)
517 self.assertIn('__gt__', C.__dict__)
518 self.assertIn('__ge__', C.__dict__)
519 elif result == 'eq_only':
520 self.assertIn('__eq__', C.__dict__)
521 self.assertNotIn('__lt__', C.__dict__)
522 self.assertNotIn('__le__', C.__dict__)
523 self.assertNotIn('__gt__', C.__dict__)
524 self.assertNotIn('__ge__', C.__dict__)
525 else:
526 assert False, f'unknown result {result!r}'
527
528 def test_field_no_default(self):
529 @dataclass
530 class C:
531 x: int = field()
532
533 self.assertEqual(C(5).x, 5)
534
535 with self.assertRaisesRegex(TypeError,
536 r"__init__\(\) missing 1 required "
537 "positional argument: 'x'"):
538 C()
539
540 def test_field_default(self):
541 default = object()
542 @dataclass
543 class C:
544 x: object = field(default=default)
545
546 self.assertIs(C.x, default)
547 c = C(10)
548 self.assertEqual(c.x, 10)
549
550 # If we delete the instance attribute, we should then see the
551 # class attribute.
552 del c.x
553 self.assertIs(c.x, default)
554
555 self.assertIs(C().x, default)
556
557 def test_not_in_repr(self):
558 @dataclass
559 class C:
560 x: int = field(repr=False)
561 with self.assertRaises(TypeError):
562 C()
563 c = C(10)
564 self.assertEqual(repr(c), 'TestCase.test_not_in_repr.<locals>.C()')
565
566 @dataclass
567 class C:
568 x: int = field(repr=False)
569 y: int
570 c = C(10, 20)
571 self.assertEqual(repr(c), 'TestCase.test_not_in_repr.<locals>.C(y=20)')
572
573 def test_not_in_compare(self):
574 @dataclass
575 class C:
576 x: int = 0
577 y: int = field(compare=False, default=4)
578
579 self.assertEqual(C(), C(0, 20))
580 self.assertEqual(C(1, 10), C(1, 20))
581 self.assertNotEqual(C(3), C(4, 10))
582 self.assertNotEqual(C(3, 10), C(4, 10))
583
584 def test_no_unhashable_default(self):
585 # See bpo-44674.
586 class Unhashable:
587 __hash__ = None
588
589 unhashable_re = 'mutable default .* for field a is not allowed'
590 with self.assertRaisesRegex(ValueError, unhashable_re):
591 @dataclass
592 class A:
593 a: dict = {}
594
595 with self.assertRaisesRegex(ValueError, unhashable_re):
596 @dataclass
597 class A:
598 a: Any = Unhashable()
599
600 # Make sure that the machinery looking for hashability is using the
601 # class's __hash__, not the instance's __hash__.
602 with self.assertRaisesRegex(ValueError, unhashable_re):
603 unhashable = Unhashable()
604 # This shouldn't make the variable hashable.
605 unhashable.__hash__ = lambda: 0
606 @dataclass
607 class A:
608 a: Any = unhashable
609
610 def test_hash_field_rules(self):
611 # Test all 6 cases of:
612 # hash=True/False/None
613 # compare=True/False
614 for (hash_, compare, result ) in [
615 (True, False, 'field' ),
616 (True, True, 'field' ),
617 (False, False, 'absent'),
618 (False, True, 'absent'),
619 (None, False, 'absent'),
620 (None, True, 'field' ),
621 ]:
622 with self.subTest(hash=hash_, compare=compare):
623 @dataclass(unsafe_hash=True)
624 class C:
625 x: int = field(compare=compare, hash=hash_, default=5)
626
627 if result == 'field':
628 # __hash__ contains the field.
629 self.assertEqual(hash(C(5)), hash((5,)))
630 elif result == 'absent':
631 # The field is not present in the hash.
632 self.assertEqual(hash(C(5)), hash(()))
633 else:
634 assert False, f'unknown result {result!r}'
635
636 def test_init_false_no_default(self):
637 # If init=False and no default value, then the field won't be
638 # present in the instance.
639 @dataclass
640 class C:
641 x: int = field(init=False)
642
643 self.assertNotIn('x', C().__dict__)
644
645 @dataclass
646 class C:
647 x: int
648 y: int = 0
649 z: int = field(init=False)
650 t: int = 10
651
652 self.assertNotIn('z', C(0).__dict__)
653 self.assertEqual(vars(C(5)), {'t': 10, 'x': 5, 'y': 0})
654
655 def test_class_marker(self):
656 @dataclass
657 class C:
658 x: int
659 y: str = field(init=False, default=None)
660 z: str = field(repr=False)
661
662 the_fields = fields(C)
663 # the_fields is a tuple of 3 items, each value
664 # is in __annotations__.
665 self.assertIsInstance(the_fields, tuple)
666 for f in the_fields:
667 self.assertIs(type(f), Field)
668 self.assertIn(f.name, C.__annotations__)
669
670 self.assertEqual(len(the_fields), 3)
671
672 self.assertEqual(the_fields[0].name, 'x')
673 self.assertEqual(the_fields[0].type, int)
674 self.assertNotHasAttr(C, 'x')
675 self.assertTrue (the_fields[0].init)
676 self.assertTrue (the_fields[0].repr)
677 self.assertEqual(the_fields[1].name, 'y')
678 self.assertEqual(the_fields[1].type, str)
679 self.assertIsNone(getattr(C, 'y'))
680 self.assertFalse(the_fields[1].init)
681 self.assertTrue (the_fields[1].repr)
682 self.assertEqual(the_fields[2].name, 'z')
683 self.assertEqual(the_fields[2].type, str)
684 self.assertNotHasAttr(C, 'z')
685 self.assertTrue (the_fields[2].init)
686 self.assertFalse(the_fields[2].repr)
687
688 def test_field_order(self):
689 @dataclass
690 class B:
691 a: str = 'B:a'
692 b: str = 'B:b'
693 c: str = 'B:c'
694
695 @dataclass
696 class C(B):
697 b: str = 'C:b'
698
699 self.assertEqual([(f.name, f.default) for f in fields(C)],
700 [('a', 'B:a'),
701 ('b', 'C:b'),
702 ('c', 'B:c')])
703
704 @dataclass
705 class D(B):
706 c: str = 'D:c'
707
708 self.assertEqual([(f.name, f.default) for f in fields(D)],
709 [('a', 'B:a'),
710 ('b', 'B:b'),
711 ('c', 'D:c')])
712
713 @dataclass
714 class E(D):
715 a: str = 'E:a'
716 d: str = 'E:d'
717
718 self.assertEqual([(f.name, f.default) for f in fields(E)],
719 [('a', 'E:a'),
720 ('b', 'B:b'),
721 ('c', 'D:c'),
722 ('d', 'E:d')])
723
724 def test_class_attrs(self):
725 # We only have a class attribute if a default value is
726 # specified, either directly or via a field with a default.
727 default = object()
728 @dataclass
729 class C:
730 x: int
731 y: int = field(repr=False)
732 z: object = default
733 t: int = field(default=100)
734
735 self.assertNotHasAttr(C, 'x')
736 self.assertNotHasAttr(C, 'y')
737 self.assertIs (C.z, default)
738 self.assertEqual(C.t, 100)
739
740 def test_disallowed_mutable_defaults(self):
741 # For the known types, don't allow mutable default values.
742 for typ, empty, non_empty in [(list, [], [1]),
743 (dict, {}, {0:1}),
744 (set, set(), set([1])),
745 ]:
746 with self.subTest(typ=typ):
747 # Can't use a zero-length value.
748 with self.assertRaisesRegex(ValueError,
749 f'mutable default {typ} for field '
750 'x is not allowed'):
751 @dataclass
752 class Point:
753 x: typ = empty
754
755
756 # Nor a non-zero-length value
757 with self.assertRaisesRegex(ValueError,
758 f'mutable default {typ} for field '
759 'y is not allowed'):
760 @dataclass
761 class Point:
762 y: typ = non_empty
763
764 # Check subtypes also fail.
765 class Subclass(typ): pass
766
767 with self.assertRaisesRegex(ValueError,
768 "mutable default .*Subclass'>"
769 " for field z is not allowed"
770 ):
771 @dataclass
772 class Point:
773 z: typ = Subclass()
774
775 # Because this is a ClassVar, it can be mutable.
776 @dataclass
777 class UsesMutableClassVar:
778 z: ClassVar[typ] = typ()
779
780 # Because this is a ClassVar, it can be mutable.
781 @dataclass
782 class UsesMutableClassVarWithSubType:
783 x: ClassVar[typ] = Subclass()
784
785 def test_deliberately_mutable_defaults(self):
786 # If a mutable default isn't in the known list of
787 # (list, dict, set), then it's okay.
788 class Mutable:
789 def __init__(self):
790 self.l = []
791
792 @dataclass
793 class C:
794 x: Mutable
795
796 # These 2 instances will share this value of x.
797 lst = Mutable()
798 o1 = C(lst)
799 o2 = C(lst)
800 self.assertEqual(o1, o2)
801 o1.x.l.extend([1, 2])
802 self.assertEqual(o1, o2)
803 self.assertEqual(o1.x.l, [1, 2])
804 self.assertIs(o1.x, o2.x)
805
806 def test_no_options(self):
807 # Call with dataclass().
808 @dataclass()
809 class C:
810 x: int
811
812 self.assertEqual(C(42).x, 42)
813
814 def test_not_tuple(self):
815 # Make sure we can't be compared to a tuple.
816 @dataclass
817 class Point:
818 x: int
819 y: int
820 self.assertNotEqual(Point(1, 2), (1, 2))
821
822 # And that we can't compare to another unrelated dataclass.
823 @dataclass
824 class C:
825 x: int
826 y: int
827 self.assertNotEqual(Point(1, 3), C(1, 3))
828
829 def test_not_other_dataclass(self):
830 # Test that some of the problems with namedtuple don't happen
831 # here.
832 @dataclass
833 class Point3D:
834 x: int
835 y: int
836 z: int
837
838 @dataclass
839 class Date:
840 year: int
841 month: int
842 day: int
843
844 self.assertNotEqual(Point3D(2017, 6, 3), Date(2017, 6, 3))
845 self.assertNotEqual(Point3D(1, 2, 3), (1, 2, 3))
846
847 # Make sure we can't unpack.
848 with self.assertRaisesRegex(TypeError, 'unpack'):
849 x, y, z = Point3D(4, 5, 6)
850
851 # Make sure another class with the same field names isn't
852 # equal.
853 @dataclass
854 class Point3Dv1:
855 x: int = 0
856 y: int = 0
857 z: int = 0
858 self.assertNotEqual(Point3D(0, 0, 0), Point3Dv1())
859
860 def test_function_annotations(self):
861 # Some dummy class and instance to use as a default.
862 class F:
863 pass
864 f = F()
865
866 def validate_class(cls):
867 # First, check __annotations__, even though they're not
868 # function annotations.
869 self.assertEqual(cls.__annotations__['i'], int)
870 self.assertEqual(cls.__annotations__['j'], str)
871 self.assertEqual(cls.__annotations__['k'], F)
872 self.assertEqual(cls.__annotations__['l'], float)
873 self.assertEqual(cls.__annotations__['z'], complex)
874
875 # Verify __init__.
876
877 signature = inspect.signature(cls.__init__)
878 # Check the return type, should be None.
879 self.assertIs(signature.return_annotation, None)
880
881 # Check each parameter.
882 params = iter(signature.parameters.values())
883 param = next(params)
884 # This is testing an internal name, and probably shouldn't be tested.
885 self.assertEqual(param.name, 'self')
886 param = next(params)
887 self.assertEqual(param.name, 'i')
888 self.assertIs (param.annotation, int)
889 self.assertEqual(param.default, inspect.Parameter.empty)
890 self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_OR_KEYWORD)
891 param = next(params)
892 self.assertEqual(param.name, 'j')
893 self.assertIs (param.annotation, str)
894 self.assertEqual(param.default, inspect.Parameter.empty)
895 self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_OR_KEYWORD)
896 param = next(params)
897 self.assertEqual(param.name, 'k')
898 self.assertIs (param.annotation, F)
899 # Don't test for the default, since it's set to MISSING.
900 self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_OR_KEYWORD)
901 param = next(params)
902 self.assertEqual(param.name, 'l')
903 self.assertIs (param.annotation, float)
904 # Don't test for the default, since it's set to MISSING.
905 self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_OR_KEYWORD)
906 self.assertRaises(StopIteration, next, params)
907
908
909 @dataclass
910 class C:
911 i: int
912 j: str
913 k: F = f
914 l: float=field(default=None)
915 z: complex=field(default=3+4j, init=False)
916
917 validate_class(C)
918
919 # Now repeat with __hash__.
920 @dataclass(frozen=True, unsafe_hash=True)
921 class C:
922 i: int
923 j: str
924 k: F = f
925 l: float=field(default=None)
926 z: complex=field(default=3+4j, init=False)
927
928 validate_class(C)
929
930 def test_incomplete_annotations(self):
931 # gh-142214
932 @dataclass
933 class C:
934 "doc" # needed because otherwise we fetch the annotations at the wrong time
935 x: int
936
937 C.__annotate__ = lambda _: {}
938
939 self.assertEqual(
940 annotationlib.get_annotations(C.__init__),
941 {"return": None}
942 )
943
944 def test_missing_default(self):
945 # Test that MISSING works the same as a default not being
946 # specified.
947 @dataclass
948 class C:
949 x: int=field(default=MISSING)
950 with self.assertRaisesRegex(TypeError,
951 r'__init__\(\) missing 1 required '
952 'positional argument'):
953 C()
954 self.assertNotIn('x', C.__dict__)
955
956 @dataclass
957 class D:
958 x: int
959 with self.assertRaisesRegex(TypeError,
960 r'__init__\(\) missing 1 required '
961 'positional argument'):
962 D()
963 self.assertNotIn('x', D.__dict__)
964
965 def test_missing_default_factory(self):
966 # Test that MISSING works the same as a default factory not
967 # being specified (which is really the same as a default not
968 # being specified, too).
969 @dataclass
970 class C:
971 x: int=field(default_factory=MISSING)
972 with self.assertRaisesRegex(TypeError,
973 r'__init__\(\) missing 1 required '
974 'positional argument'):
975 C()
976 self.assertNotIn('x', C.__dict__)
977
978 @dataclass
979 class D:
980 x: int=field(default=MISSING, default_factory=MISSING)
981 with self.assertRaisesRegex(TypeError,
982 r'__init__\(\) missing 1 required '
983 'positional argument'):
984 D()
985 self.assertNotIn('x', D.__dict__)
986
987 def test_missing_repr(self):
988 self.assertIn('MISSING_TYPE object', repr(MISSING))
989
990 def test_dont_include_other_annotations(self):
991 @dataclass
992 class C:
993 i: int
994 def foo(self) -> int:
995 return 4
996 @property
997 def bar(self) -> int:
998 return 5
999 self.assertEqual(list(C.__annotations__), ['i'])
1000 self.assertEqual(C(10).foo(), 4)
1001 self.assertEqual(C(10).bar, 5)
1002 self.assertEqual(C(10).i, 10)
1003
1004 def test_post_init(self):
1005 # Just make sure it gets called
1006 @dataclass
1007 class C:
1008 def __post_init__(self):
1009 raise CustomError()
1010 with self.assertRaises(CustomError):
1011 C()
1012
1013 @dataclass
1014 class C:
1015 i: int = 10
1016 def __post_init__(self):
1017 if self.i == 10:
1018 raise CustomError()
1019 with self.assertRaises(CustomError):
1020 C()
1021 # post-init gets called, but doesn't raise. This is just
1022 # checking that self is used correctly.
1023 C(5)
1024
1025 # If there's not an __init__, then post-init won't get called.
1026 @dataclass(init=False)
1027 class C:
1028 def __post_init__(self):
1029 raise CustomError()
1030 # Creating the class won't raise
1031 C()
1032
1033 @dataclass
1034 class C:
1035 x: int = 0
1036 def __post_init__(self):
1037 self.x *= 2
1038 self.assertEqual(C().x, 0)
1039 self.assertEqual(C(2).x, 4)
1040
1041 # Make sure that if we're frozen, post-init can't set
1042 # attributes.
1043 @dataclass(frozen=True)
1044 class C:
1045 x: int = 0
1046 def __post_init__(self):
1047 self.x *= 2
1048 with self.assertRaises(FrozenInstanceError):
1049 C()
1050
1051 def test_post_init_super(self):
1052 # Make sure super() post-init isn't called by default.
1053 class B:
1054 def __post_init__(self):
1055 raise CustomError()
1056
1057 @dataclass
1058 class C(B):
1059 def __post_init__(self):
1060 self.x = 5
1061
1062 self.assertEqual(C().x, 5)
1063
1064 # Now call super(), and it will raise.
1065 @dataclass
1066 class C(B):
1067 def __post_init__(self):
1068 super().__post_init__()
1069
1070 with self.assertRaises(CustomError):
1071 C()
1072
1073 # Make sure post-init is called, even if not defined in our
1074 # class.
1075 @dataclass
1076 class C(B):
1077 pass
1078
1079 with self.assertRaises(CustomError):
1080 C()
1081
1082 def test_post_init_staticmethod(self):
1083 flag = False
1084 @dataclass
1085 class C:
1086 x: int
1087 y: int
1088 @staticmethod
1089 def __post_init__():
1090 nonlocal flag
1091 flag = True
1092
1093 self.assertFalse(flag)
1094 c = C(3, 4)
1095 self.assertEqual((c.x, c.y), (3, 4))
1096 self.assertTrue(flag)
1097
1098 def test_post_init_classmethod(self):
1099 @dataclass
1100 class C:
1101 flag = False
1102 x: int
1103 y: int
1104 @classmethod
1105 def __post_init__(cls):
1106 cls.flag = True
1107
1108 self.assertFalse(C.flag)
1109 c = C(3, 4)
1110 self.assertEqual((c.x, c.y), (3, 4))
1111 self.assertTrue(C.flag)
1112
1113 def test_post_init_not_auto_added(self):
1114 # See bpo-46757, which had proposed always adding __post_init__. As
1115 # Raymond Hettinger pointed out, that would be a breaking change. So,
1116 # add a test to make sure that the current behavior doesn't change.
1117
1118 @dataclass
1119 class A0:
1120 pass
1121
1122 @dataclass
1123 class B0:
1124 b_called: bool = False
1125 def __post_init__(self):
1126 self.b_called = True
1127
1128 @dataclass
1129 class C0(A0, B0):
1130 c_called: bool = False
1131 def __post_init__(self):
1132 super().__post_init__()
1133 self.c_called = True
1134
1135 # Since A0 has no __post_init__, and one wasn't automatically added
1136 # (because that's the rule: it's never added by @dataclass, it's only
1137 # the class author that can add it), then B0.__post_init__ is called.
1138 # Verify that.
1139 c = C0()
1140 self.assertTrue(c.b_called)
1141 self.assertTrue(c.c_called)
1142
1143 ######################################
1144 # Now, the same thing, except A1 defines __post_init__.
1145 @dataclass
1146 class A1:
1147 def __post_init__(self):
1148 pass
1149
1150 @dataclass
1151 class B1:
1152 b_called: bool = False
1153 def __post_init__(self):
1154 self.b_called = True
1155
1156 @dataclass
1157 class C1(A1, B1):
1158 c_called: bool = False
1159 def __post_init__(self):
1160 super().__post_init__()
1161 self.c_called = True
1162
1163 # This time, B1.__post_init__ isn't being called. This mimics what
1164 # would happen if A1.__post_init__ had been automatically added,
1165 # instead of manually added as we see here. This test isn't really
1166 # needed, but I'm including it just to demonstrate the changed
1167 # behavior when A1 does define __post_init__.
1168 c = C1()
1169 self.assertFalse(c.b_called)
1170 self.assertTrue(c.c_called)
1171
1172 def test_class_var(self):
1173 # Make sure ClassVars are ignored in __init__, __repr__, etc.
1174 @dataclass
1175 class C:
1176 x: int
1177 y: int = 10
1178 z: ClassVar[int] = 1000
1179 w: ClassVar[int] = 2000
1180 t: ClassVar[int] = 3000
1181 s: ClassVar = 4000
1182
1183 c = C(5)
1184 self.assertEqual(repr(c), 'TestCase.test_class_var.<locals>.C(x=5, y=10)')
1185 self.assertEqual(len(fields(C)), 2) # We have 2 fields.
1186 self.assertEqual(len(C.__annotations__), 6) # And 4 ClassVars.
1187 self.assertEqual(c.z, 1000)
1188 self.assertEqual(c.w, 2000)
1189 self.assertEqual(c.t, 3000)
1190 self.assertEqual(c.s, 4000)
1191 C.z += 1
1192 self.assertEqual(c.z, 1001)
1193 c = C(20)
1194 self.assertEqual((c.x, c.y), (20, 10))
1195 self.assertEqual(c.z, 1001)
1196 self.assertEqual(c.w, 2000)
1197 self.assertEqual(c.t, 3000)
1198 self.assertEqual(c.s, 4000)
1199
1200 def test_class_var_no_default(self):
1201 # If a ClassVar has no default value, it should not be set on the class.
1202 @dataclass
1203 class C:
1204 x: ClassVar[int]
1205
1206 self.assertNotIn('x', C.__dict__)
1207
1208 def test_class_var_default_factory(self):
1209 # It makes no sense for a ClassVar to have a default factory. When
1210 # would it be called? Call it yourself, since it's class-wide.
1211 with self.assertRaisesRegex(TypeError,
1212 'cannot have a default factory'):
1213 @dataclass
1214 class C:
1215 x: ClassVar[int] = field(default_factory=int)
1216
1217 self.assertNotIn('x', C.__dict__)
1218
1219 def test_class_var_with_default(self):
1220 # If a ClassVar has a default value, it should be set on the class.
1221 @dataclass
1222 class C:
1223 x: ClassVar[int] = 10
1224 self.assertEqual(C.x, 10)
1225
1226 @dataclass
1227 class C:
1228 x: ClassVar[int] = field(default=10)
1229 self.assertEqual(C.x, 10)
1230
1231 def test_class_var_frozen(self):
1232 # Make sure ClassVars work even if we're frozen.
1233 @dataclass(frozen=True)
1234 class C:
1235 x: int
1236 y: int = 10
1237 z: ClassVar[int] = 1000
1238 w: ClassVar[int] = 2000
1239 t: ClassVar[int] = 3000
1240
1241 c = C(5)
1242 self.assertEqual(repr(C(5)), 'TestCase.test_class_var_frozen.<locals>.C(x=5, y=10)')
1243 self.assertEqual(len(fields(C)), 2) # We have 2 fields
1244 self.assertEqual(len(C.__annotations__), 5) # And 3 ClassVars
1245 self.assertEqual(c.z, 1000)
1246 self.assertEqual(c.w, 2000)
1247 self.assertEqual(c.t, 3000)
1248 # We can still modify the ClassVar, it's only instances that are
1249 # frozen.
1250 C.z += 1
1251 self.assertEqual(c.z, 1001)
1252 c = C(20)
1253 self.assertEqual((c.x, c.y), (20, 10))
1254 self.assertEqual(c.z, 1001)
1255 self.assertEqual(c.w, 2000)
1256 self.assertEqual(c.t, 3000)
1257
1258 def test_init_var_no_default(self):
1259 # If an InitVar has no default value, it should not be set on the class.
1260 @dataclass
1261 class C:
1262 x: InitVar[int]
1263
1264 self.assertNotIn('x', C.__dict__)
1265
1266 def test_init_var_default_factory(self):
1267 # It makes no sense for an InitVar to have a default factory. When
1268 # would it be called? Call it yourself, since it's class-wide.
1269 with self.assertRaisesRegex(TypeError,
1270 'cannot have a default factory'):
1271 @dataclass
1272 class C:
1273 x: InitVar[int] = field(default_factory=int)
1274
1275 self.assertNotIn('x', C.__dict__)
1276
1277 def test_init_var_with_default(self):
1278 # If an InitVar has a default value, it should be set on the class.
1279 @dataclass
1280 class C:
1281 x: InitVar[int] = 10
1282 self.assertEqual(C.x, 10)
1283
1284 @dataclass
1285 class C:
1286 x: InitVar[int] = field(default=10)
1287 self.assertEqual(C.x, 10)
1288
1289 def test_init_var(self):
1290 @dataclass
1291 class C:
1292 x: int = None
1293 init_param: InitVar[int] = None
1294
1295 def __post_init__(self, init_param):
1296 if self.x is None:
1297 self.x = init_param*2
1298
1299 c = C(init_param=10)
1300 self.assertEqual(c.x, 20)
1301
1302 def test_init_var_preserve_type(self):
1303 self.assertEqual(InitVar[int].type, int)
1304
1305 # Make sure the repr is correct.
1306 self.assertEqual(repr(InitVar[int]), 'dataclasses.InitVar[int]')
1307 self.assertEqual(repr(InitVar[List[int]]),
1308 'dataclasses.InitVar[typing.List[int]]')
1309 self.assertEqual(repr(InitVar[list[int]]),
1310 'dataclasses.InitVar[list[int]]')
1311 self.assertEqual(repr(InitVar[int|str]),
1312 'dataclasses.InitVar[int | str]')
1313
1314 def test_init_var_inheritance(self):
1315 # Note that this deliberately tests that a dataclass need not
1316 # have a __post_init__ function if it has an InitVar field.
1317 # It could just be used in a derived class, as shown here.
1318 @dataclass
1319 class Base:
1320 x: int
1321 init_base: InitVar[int]
1322
1323 # We can instantiate by passing the InitVar, even though
1324 # it's not used.
1325 b = Base(0, 10)
1326 self.assertEqual(vars(b), {'x': 0})
1327
1328 @dataclass
1329 class C(Base):
1330 y: int
1331 init_derived: InitVar[int]
1332
1333 def __post_init__(self, init_base, init_derived):
1334 self.x = self.x + init_base
1335 self.y = self.y + init_derived
1336
1337 c = C(10, 11, 50, 51)
1338 self.assertEqual(vars(c), {'x': 21, 'y': 101})
1339
1340 def test_init_var_name_shadowing(self):
1341 # Because dataclasses rely exclusively on `__annotations__` for
1342 # handling InitVar and `__annotations__` preserves shadowed definitions,
1343 # you can actually shadow an InitVar with a method or property.
1344 #
1345 # This only works when there is no default value; `dataclasses` uses the
1346 # actual name (which will be bound to the shadowing method) for default
1347 # values.
1348 @dataclass
1349 class C:
1350 shadowed: InitVar[int]
1351 _shadowed: int = field(init=False)
1352
1353 def __post_init__(self, shadowed):
1354 self._shadowed = shadowed * 2
1355
1356 @property
1357 def shadowed(self):
1358 return self._shadowed * 3
1359
1360 c = C(5)
1361 self.assertEqual(c.shadowed, 30)
1362
1363 def test_default_factory(self):
1364 # Test a factory that returns a new list.
1365 @dataclass
1366 class C:
1367 x: int
1368 y: list = field(default_factory=list)
1369
1370 c0 = C(3)
1371 c1 = C(3)
1372 self.assertEqual(c0.x, 3)
1373 self.assertEqual(c0.y, [])
1374 self.assertEqual(c0, c1)
1375 self.assertIsNot(c0.y, c1.y)
1376 self.assertEqual(astuple(C(5, [1])), (5, [1]))
1377
1378 # Test a factory that returns a shared list.
1379 l = []
1380 @dataclass
1381 class C:
1382 x: int
1383 y: list = field(default_factory=lambda: l)
1384
1385 c0 = C(3)
1386 c1 = C(3)
1387 self.assertEqual(c0.x, 3)
1388 self.assertEqual(c0.y, [])
1389 self.assertEqual(c0, c1)
1390 self.assertIs(c0.y, c1.y)
1391 self.assertEqual(astuple(C(5, [1])), (5, [1]))
1392
1393 # Test various other field flags.
1394 # repr
1395 @dataclass
1396 class C:
1397 x: list = field(default_factory=list, repr=False)
1398 self.assertEqual(repr(C()), 'TestCase.test_default_factory.<locals>.C()')
1399 self.assertEqual(C().x, [])
1400
1401 # hash
1402 @dataclass(unsafe_hash=True)
1403 class C:
1404 x: list = field(default_factory=list, hash=False)
1405 self.assertEqual(astuple(C()), ([],))
1406 self.assertEqual(hash(C()), hash(()))
1407
1408 # init (see also test_default_factory_with_no_init)
1409 @dataclass
1410 class C:
1411 x: list = field(default_factory=list, init=False)
1412 self.assertEqual(astuple(C()), ([],))
1413
1414 # compare
1415 @dataclass
1416 class C:
1417 x: list = field(default_factory=list, compare=False)
1418 self.assertEqual(C(), C([1]))
1419
1420 def test_default_factory_with_no_init(self):
1421 # We need a factory with a side effect.
1422 factory = Mock()
1423
1424 @dataclass
1425 class C:
1426 x: list = field(default_factory=factory, init=False)
1427
1428 # Make sure the default factory is called for each new instance.
1429 C().x
1430 self.assertEqual(factory.call_count, 1)
1431 C().x
1432 self.assertEqual(factory.call_count, 2)
1433
1434 def test_default_factory_not_called_if_value_given(self):
1435 # We need a factory that we can test if it's been called.
1436 factory = Mock()
1437
1438 @dataclass
1439 class C:
1440 x: int = field(default_factory=factory)
1441
1442 # Make sure that if a field has a default factory function,
1443 # it's not called if a value is specified.
1444 C().x
1445 self.assertEqual(factory.call_count, 1)
1446 self.assertEqual(C(10).x, 10)
1447 self.assertEqual(factory.call_count, 1)
1448 C().x
1449 self.assertEqual(factory.call_count, 2)
1450
1451 def test_default_factory_derived(self):
1452 # See bpo-32896.
1453 @dataclass
1454 class Foo:
1455 x: dict = field(default_factory=dict)
1456
1457 @dataclass
1458 class Bar(Foo):
1459 y: int = 1
1460
1461 self.assertEqual(Foo().x, {})
1462 self.assertEqual(Bar().x, {})
1463 self.assertEqual(Bar().y, 1)
1464
1465 @dataclass
1466 class Baz(Foo):
1467 pass
1468 self.assertEqual(Baz().x, {})
1469
1470 def test_intermediate_non_dataclass(self):
1471 # Test that an intermediate class that defines
1472 # annotations does not define fields.
1473
1474 @dataclass
1475 class A:
1476 x: int
1477
1478 class B(A):
1479 y: int
1480
1481 @dataclass
1482 class C(B):
1483 z: int
1484
1485 c = C(1, 3)
1486 self.assertEqual((c.x, c.z), (1, 3))
1487
1488 # .y was not initialized.
1489 with self.assertRaisesRegex(AttributeError,
1490 'object has no attribute'):
1491 c.y
1492
1493 # And if we again derive a non-dataclass, no fields are added.
1494 class D(C):
1495 t: int
1496 d = D(4, 5)
1497 self.assertEqual((d.x, d.z), (4, 5))
1498
1499 def test_classvar_default_factory(self):
1500 # It's an error for a ClassVar to have a factory function.
1501 with self.assertRaisesRegex(TypeError,
1502 'cannot have a default factory'):
1503 @dataclass
1504 class C:
1505 x: ClassVar[int] = field(default_factory=int)
1506
1507 def test_is_dataclass(self):
1508 class NotDataClass:
1509 pass
1510
1511 self.assertFalse(is_dataclass(0))
1512 self.assertFalse(is_dataclass(int))
1513 self.assertFalse(is_dataclass(NotDataClass))
1514 self.assertFalse(is_dataclass(NotDataClass()))
1515
1516 @dataclass
1517 class C:
1518 x: int
1519
1520 @dataclass
1521 class D:
1522 d: C
1523 e: int
1524
1525 c = C(10)
1526 d = D(c, 4)
1527
1528 self.assertTrue(is_dataclass(C))
1529 self.assertTrue(is_dataclass(c))
1530 self.assertFalse(is_dataclass(c.x))
1531 self.assertTrue(is_dataclass(d.d))
1532 self.assertFalse(is_dataclass(d.e))
1533
1534 def test_is_dataclass_when_getattr_always_returns(self):
1535 # See bpo-37868.
1536 class A:
1537 def __getattr__(self, key):
1538 return 0
1539 self.assertFalse(is_dataclass(A))
1540 a = A()
1541
1542 # Also test for an instance attribute.
1543 class B:
1544 pass
1545 b = B()
1546 b.__dataclass_fields__ = []
1547
1548 for obj in a, b:
1549 with self.subTest(obj=obj):
1550 self.assertFalse(is_dataclass(obj))
1551
1552 # Indirect tests for _is_dataclass_instance().
1553 with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'):
1554 asdict(obj)
1555 with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'):
1556 astuple(obj)
1557 with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'):
1558 replace(obj, x=0)
1559
1560 def test_is_dataclass_genericalias(self):
1561 @dataclass
1562 class A(types.GenericAlias):
1563 origin: type
1564 args: type
1565 self.assertTrue(is_dataclass(A))
1566 a = A(list, int)
1567 self.assertTrue(is_dataclass(type(a)))
1568 self.assertTrue(is_dataclass(a))
1569
1570 def test_is_dataclass_inheritance(self):
1571 @dataclass
1572 class X:
1573 y: int
1574
1575 class Z(X):
1576 pass
1577
1578 self.assertTrue(is_dataclass(X), "X should be a dataclass")
1579 self.assertTrue(
1580 is_dataclass(Z),
1581 "Z should be a dataclass because it inherits from X",
1582 )
1583 z_instance = Z(y=5)
1584 self.assertTrue(
1585 is_dataclass(z_instance),
1586 "z_instance should be a dataclass because it is an instance of Z",
1587 )
1588
1589 def test_helper_fields_with_class_instance(self):
1590 # Check that we can call fields() on either a class or instance,
1591 # and get back the same thing.
1592 @dataclass
1593 class C:
1594 x: int
1595 y: float
1596
1597 self.assertEqual(fields(C), fields(C(0, 0.0)))
1598
1599 def test_helper_fields_exception(self):
1600 # Check that TypeError is raised if not passed a dataclass or
1601 # instance.
1602 with self.assertRaisesRegex(TypeError, 'dataclass type or instance'):
1603 fields(0)
1604
1605 class C: pass
1606 with self.assertRaisesRegex(TypeError, 'dataclass type or instance'):
1607 fields(C)
1608 with self.assertRaisesRegex(TypeError, 'dataclass type or instance'):
1609 fields(C())
1610
1611 def test_clean_traceback_from_fields_exception(self):
1612 stdout = io.StringIO()
1613 try:
1614 fields(object)
1615 except TypeError as exc:
1616 traceback.print_exception(exc, file=stdout)
1617 printed_traceback = stdout.getvalue()
1618 self.assertNotIn("AttributeError", printed_traceback)
1619 self.assertNotIn("__dataclass_fields__", printed_traceback)
1620
1621 def test_helper_asdict(self):
1622 # Basic tests for asdict(), it should return a new dictionary.
1623 @dataclass
1624 class C:
1625 x: int
1626 y: int
1627 c = C(1, 2)
1628
1629 self.assertEqual(asdict(c), {'x': 1, 'y': 2})
1630 self.assertEqual(asdict(c), asdict(c))
1631 self.assertIsNot(asdict(c), asdict(c))
1632 c.x = 42
1633 self.assertEqual(asdict(c), {'x': 42, 'y': 2})
1634 self.assertIs(type(asdict(c)), dict)
1635
1636 def test_helper_asdict_raises_on_classes(self):
1637 # asdict() should raise on a class object.
1638 @dataclass
1639 class C:
1640 x: int
1641 y: int
1642 with self.assertRaisesRegex(TypeError, 'dataclass instance'):
1643 asdict(C)
1644 with self.assertRaisesRegex(TypeError, 'dataclass instance'):
1645 asdict(int)
1646
1647 def test_helper_asdict_copy_values(self):
1648 @dataclass
1649 class C:
1650 x: int
1651 y: List[int] = field(default_factory=list)
1652 initial = []
1653 c = C(1, initial)
1654 d = asdict(c)
1655 self.assertEqual(d['y'], initial)
1656 self.assertIsNot(d['y'], initial)
1657 c = C(1)
1658 d = asdict(c)
1659 d['y'].append(1)
1660 self.assertEqual(c.y, [])
1661
1662 def test_helper_asdict_nested(self):
1663 @dataclass
1664 class UserId:
1665 token: int
1666 group: int
1667 @dataclass
1668 class User:
1669 name: str
1670 id: UserId
1671 u = User('Joe', UserId(123, 1))
1672 d = asdict(u)
1673 self.assertEqual(d, {'name': 'Joe', 'id': {'token': 123, 'group': 1}})
1674 self.assertIsNot(asdict(u), asdict(u))
1675 u.id.group = 2
1676 self.assertEqual(asdict(u), {'name': 'Joe',
1677 'id': {'token': 123, 'group': 2}})
1678
1679 def test_helper_asdict_builtin_containers(self):
1680 @dataclass
1681 class User:
1682 name: str
1683 id: int
1684 @dataclass
1685 class GroupList:
1686 id: int
1687 users: List[User]
1688 @dataclass
1689 class GroupTuple:
1690 id: int
1691 users: Tuple[User, ...]
1692 @dataclass
1693 class GroupDict:
1694 id: int
1695 users: Dict[str, User]
1696 a = User('Alice', 1)
1697 b = User('Bob', 2)
1698 gl = GroupList(0, [a, b])
1699 gt = GroupTuple(0, (a, b))
1700 gd = GroupDict(0, {'first': a, 'second': b})
1701 self.assertEqual(asdict(gl), {'id': 0, 'users': [{'name': 'Alice', 'id': 1},
1702 {'name': 'Bob', 'id': 2}]})
1703 self.assertEqual(asdict(gt), {'id': 0, 'users': ({'name': 'Alice', 'id': 1},
1704 {'name': 'Bob', 'id': 2})})
1705 self.assertEqual(asdict(gd), {'id': 0, 'users': {'first': {'name': 'Alice', 'id': 1},
1706 'second': {'name': 'Bob', 'id': 2}}})
1707
1708 def test_helper_asdict_builtin_object_containers(self):
1709 @dataclass
1710 class Child:
1711 d: object
1712
1713 @dataclass
1714 class Parent:
1715 child: Child
1716
1717 self.assertEqual(asdict(Parent(Child([1]))), {'child': {'d': [1]}})
1718 self.assertEqual(asdict(Parent(Child({1: 2}))), {'child': {'d': {1: 2}}})
1719
1720 def test_helper_asdict_factory(self):
1721 @dataclass
1722 class C:
1723 x: int
1724 y: int
1725 c = C(1, 2)
1726 d = asdict(c, dict_factory=OrderedDict)
1727 self.assertEqual(d, OrderedDict([('x', 1), ('y', 2)]))
1728 self.assertIsNot(d, asdict(c, dict_factory=OrderedDict))
1729 c.x = 42
1730 d = asdict(c, dict_factory=OrderedDict)
1731 self.assertEqual(d, OrderedDict([('x', 42), ('y', 2)]))
1732 self.assertIs(type(d), OrderedDict)
1733
1734 def test_helper_asdict_namedtuple(self):
1735 T = namedtuple('T', 'a b c')
1736 @dataclass
1737 class C:
1738 x: str
1739 y: T
1740 c = C('outer', T(1, C('inner', T(11, 12, 13)), 2))
1741
1742 d = asdict(c)
1743 self.assertEqual(d, {'x': 'outer',
1744 'y': T(1,
1745 {'x': 'inner',
1746 'y': T(11, 12, 13)},
1747 2),
1748 }
1749 )
1750
1751 # Now with a dict_factory. OrderedDict is convenient, but
1752 # since it compares to dicts, we also need to have separate
1753 # assertIs tests.
1754 d = asdict(c, dict_factory=OrderedDict)
1755 self.assertEqual(d, {'x': 'outer',
1756 'y': T(1,
1757 {'x': 'inner',
1758 'y': T(11, 12, 13)},
1759 2),
1760 }
1761 )
1762
1763 # Make sure that the returned dicts are actually OrderedDicts.
1764 self.assertIs(type(d), OrderedDict)
1765 self.assertIs(type(d['y'][1]), OrderedDict)
1766
1767 def test_helper_asdict_namedtuple_key(self):
1768 # Ensure that a field that contains a dict which has a
1769 # namedtuple as a key works with asdict().
1770
1771 @dataclass
1772 class C:
1773 f: dict
1774 T = namedtuple('T', 'a')
1775
1776 c = C({T('an a'): 0})
1777
1778 self.assertEqual(asdict(c), {'f': {T(a='an a'): 0}})
1779
1780 def test_helper_asdict_namedtuple_derived(self):
1781 class T(namedtuple('Tbase', 'a')):
1782 def my_a(self):
1783 return self.a
1784
1785 @dataclass
1786 class C:
1787 f: T
1788
1789 t = T(6)
1790 c = C(t)
1791
1792 d = asdict(c)
1793 self.assertEqual(d, {'f': T(a=6)})
1794 # Make sure that t has been copied, not used directly.
1795 self.assertIsNot(d['f'], t)
1796 self.assertEqual(d['f'].my_a(), 6)
1797
1798 def test_helper_asdict_defaultdict(self):
1799 # Ensure asdict() does not throw exceptions when a
1800 # defaultdict is a member of a dataclass
1801 @dataclass
1802 class C:
1803 mp: DefaultDict[str, List]
1804
1805 dd = defaultdict(list)
1806 dd["x"].append(12)
1807 c = C(mp=dd)
1808 d = asdict(c)
1809
1810 self.assertEqual(d, {"mp": {"x": [12]}})
1811 self.assertTrue(d["mp"] is not c.mp) # make sure defaultdict is copied
1812
1813 def test_helper_astuple(self):
1814 # Basic tests for astuple(), it should return a new tuple.
1815 @dataclass
1816 class C:
1817 x: int
1818 y: int = 0
1819 c = C(1)
1820
1821 self.assertEqual(astuple(c), (1, 0))
1822 self.assertEqual(astuple(c), astuple(c))
1823 self.assertIsNot(astuple(c), astuple(c))
1824 c.y = 42
1825 self.assertEqual(astuple(c), (1, 42))
1826 self.assertIs(type(astuple(c)), tuple)
1827
1828 def test_helper_astuple_raises_on_classes(self):
1829 # astuple() should raise on a class object.
1830 @dataclass
1831 class C:
1832 x: int
1833 y: int
1834 with self.assertRaisesRegex(TypeError, 'dataclass instance'):
1835 astuple(C)
1836 with self.assertRaisesRegex(TypeError, 'dataclass instance'):
1837 astuple(int)
1838
1839 def test_helper_astuple_copy_values(self):
1840 @dataclass
1841 class C:
1842 x: int
1843 y: List[int] = field(default_factory=list)
1844 initial = []
1845 c = C(1, initial)
1846 t = astuple(c)
1847 self.assertEqual(t[1], initial)
1848 self.assertIsNot(t[1], initial)
1849 c = C(1)
1850 t = astuple(c)
1851 t[1].append(1)
1852 self.assertEqual(c.y, [])
1853
1854 def test_helper_astuple_nested(self):
1855 @dataclass
1856 class UserId:
1857 token: int
1858 group: int
1859 @dataclass
1860 class User:
1861 name: str
1862 id: UserId
1863 u = User('Joe', UserId(123, 1))
1864 t = astuple(u)
1865 self.assertEqual(t, ('Joe', (123, 1)))
1866 self.assertIsNot(astuple(u), astuple(u))
1867 u.id.group = 2
1868 self.assertEqual(astuple(u), ('Joe', (123, 2)))
1869
1870 def test_helper_astuple_builtin_containers(self):
1871 @dataclass
1872 class User:
1873 name: str
1874 id: int
1875 @dataclass
1876 class GroupList:
1877 id: int
1878 users: List[User]
1879 @dataclass
1880 class GroupTuple:
1881 id: int
1882 users: Tuple[User, ...]
1883 @dataclass
1884 class GroupDict:
1885 id: int
1886 users: Dict[str, User]
1887 a = User('Alice', 1)
1888 b = User('Bob', 2)
1889 gl = GroupList(0, [a, b])
1890 gt = GroupTuple(0, (a, b))
1891 gd = GroupDict(0, {'first': a, 'second': b})
1892 self.assertEqual(astuple(gl), (0, [('Alice', 1), ('Bob', 2)]))
1893 self.assertEqual(astuple(gt), (0, (('Alice', 1), ('Bob', 2))))
1894 self.assertEqual(astuple(gd), (0, {'first': ('Alice', 1), 'second': ('Bob', 2)}))
1895
1896 def test_helper_astuple_builtin_object_containers(self):
1897 @dataclass
1898 class Child:
1899 d: object
1900
1901 @dataclass
1902 class Parent:
1903 child: Child
1904
1905 self.assertEqual(astuple(Parent(Child([1]))), (([1],),))
1906 self.assertEqual(astuple(Parent(Child({1: 2}))), (({1: 2},),))
1907
1908 def test_helper_astuple_factory(self):
1909 @dataclass
1910 class C:
1911 x: int
1912 y: int
1913 NT = namedtuple('NT', 'x y')
1914 def nt(lst):
1915 return NT(*lst)
1916 c = C(1, 2)
1917 t = astuple(c, tuple_factory=nt)
1918 self.assertEqual(t, NT(1, 2))
1919 self.assertIsNot(t, astuple(c, tuple_factory=nt))
1920 c.x = 42
1921 t = astuple(c, tuple_factory=nt)
1922 self.assertEqual(t, NT(42, 2))
1923 self.assertIs(type(t), NT)
1924
1925 def test_helper_astuple_namedtuple(self):
1926 T = namedtuple('T', 'a b c')
1927 @dataclass
1928 class C:
1929 x: str
1930 y: T
1931 c = C('outer', T(1, C('inner', T(11, 12, 13)), 2))
1932
1933 t = astuple(c)
1934 self.assertEqual(t, ('outer', T(1, ('inner', (11, 12, 13)), 2)))
1935
1936 # Now, using a tuple_factory. list is convenient here.
1937 t = astuple(c, tuple_factory=list)
1938 self.assertEqual(t, ['outer', T(1, ['inner', T(11, 12, 13)], 2)])
1939
1940 def test_helper_astuple_defaultdict(self):
1941 # Ensure astuple() does not throw exceptions when a
1942 # defaultdict is a member of a dataclass
1943 @dataclass
1944 class C:
1945 mp: DefaultDict[str, List]
1946
1947 dd = defaultdict(list)
1948 dd["x"].append(12)
1949 c = C(mp=dd)
1950 t = astuple(c)
1951
1952 self.assertEqual(t, ({"x": [12]},))
1953 self.assertTrue(t[0] is not dd) # make sure defaultdict is copied
1954
1955 def test_dynamic_class_creation(self):
1956 cls_dict = {'__annotations__': {'x': int, 'y': int},
1957 }
1958
1959 # Create the class.
1960 cls = type('C', (), cls_dict)
1961
1962 # Make it a dataclass.
1963 cls1 = dataclass(cls)
1964
1965 self.assertEqual(cls1, cls)
1966 self.assertEqual(asdict(cls(1, 2)), {'x': 1, 'y': 2})
1967
1968 def test_dynamic_class_creation_using_field(self):
1969 cls_dict = {'__annotations__': {'x': int, 'y': int},
1970 'y': field(default=5),
1971 }
1972
1973 # Create the class.
1974 cls = type('C', (), cls_dict)
1975
1976 # Make it a dataclass.
1977 cls1 = dataclass(cls)
1978
1979 self.assertEqual(cls1, cls)
1980 self.assertEqual(asdict(cls1(1)), {'x': 1, 'y': 5})
1981
1982 def test_init_in_order(self):
1983 @dataclass
1984 class C:
1985 a: int
1986 b: int = field()
1987 c: list = field(default_factory=list, init=False)
1988 d: list = field(default_factory=list)
1989 e: int = field(default=4, init=False)
1990 f: int = 4
1991
1992 calls = []
1993 def setattr(self, name, value):
1994 calls.append((name, value))
1995
1996 C.__setattr__ = setattr
1997 c = C(0, 1)
1998 self.assertEqual(('a', 0), calls[0])
1999 self.assertEqual(('b', 1), calls[1])
2000 self.assertEqual(('c', []), calls[2])
2001 self.assertEqual(('d', []), calls[3])
2002 self.assertNotIn(('e', 4), calls)
2003 self.assertEqual(('f', 4), calls[4])
2004
2005 def test_items_in_dicts(self):
2006 @dataclass
2007 class C:
2008 a: int
2009 b: list = field(default_factory=list, init=False)
2010 c: list = field(default_factory=list)
2011 d: int = field(default=4, init=False)
2012 e: int = 0
2013
2014 c = C(0)
2015 # Class dict
2016 self.assertNotIn('a', C.__dict__)
2017 self.assertNotIn('b', C.__dict__)
2018 self.assertNotIn('c', C.__dict__)
2019 self.assertIn('d', C.__dict__)
2020 self.assertEqual(C.d, 4)
2021 self.assertIn('e', C.__dict__)
2022 self.assertEqual(C.e, 0)
2023 # Instance dict
2024 self.assertIn('a', c.__dict__)
2025 self.assertEqual(c.a, 0)
2026 self.assertIn('b', c.__dict__)
2027 self.assertEqual(c.b, [])
2028 self.assertIn('c', c.__dict__)
2029 self.assertEqual(c.c, [])
2030 self.assertNotIn('d', c.__dict__)
2031 self.assertIn('e', c.__dict__)
2032 self.assertEqual(c.e, 0)
2033
2034 def test_alternate_classmethod_constructor(self):
2035 # Since __post_init__ can't take params, use a classmethod
2036 # alternate constructor. This is mostly an example to show
2037 # how to use this technique.
2038 @dataclass
2039 class C:
2040 x: int
2041 @classmethod
2042 def from_file(cls, filename):
2043 # In a real example, create a new instance
2044 # and populate 'x' from contents of a file.
2045 value_in_file = 20
2046 return cls(value_in_file)
2047
2048 self.assertEqual(C.from_file('filename').x, 20)
2049
2050 def test_field_metadata_default(self):
2051 # Make sure the default metadata is read-only and of
2052 # zero length.
2053 @dataclass
2054 class C:
2055 i: int
2056
2057 self.assertFalse(fields(C)[0].metadata)
2058 self.assertEqual(len(fields(C)[0].metadata), 0)
2059 with self.assertRaisesRegex(TypeError,
2060 'does not support item assignment'):
2061 fields(C)[0].metadata['test'] = 3
2062
2063 def test_field_metadata_mapping(self):
2064 # Make sure only a mapping can be passed as metadata
2065 # zero length.
2066 with self.assertRaises(TypeError):
2067 @dataclass
2068 class C:
2069 i: int = field(metadata=0)
2070
2071 # Make sure an empty dict works.
2072 d = {}
2073 @dataclass
2074 class C:
2075 i: int = field(metadata=d)
2076 self.assertFalse(fields(C)[0].metadata)
2077 self.assertEqual(len(fields(C)[0].metadata), 0)
2078 # Update should work (see bpo-35960).
2079 d['foo'] = 1
2080 self.assertEqual(len(fields(C)[0].metadata), 1)
2081 self.assertEqual(fields(C)[0].metadata['foo'], 1)
2082 with self.assertRaisesRegex(TypeError,
2083 'does not support item assignment'):
2084 fields(C)[0].metadata['test'] = 3
2085
2086 # Make sure a non-empty dict works.
2087 d = {'test': 10, 'bar': '42', 3: 'three'}
2088 @dataclass
2089 class C:
2090 i: int = field(metadata=d)
2091 self.assertEqual(len(fields(C)[0].metadata), 3)
2092 self.assertEqual(fields(C)[0].metadata['test'], 10)
2093 self.assertEqual(fields(C)[0].metadata['bar'], '42')
2094 self.assertEqual(fields(C)[0].metadata[3], 'three')
2095 # Update should work.
2096 d['foo'] = 1
2097 self.assertEqual(len(fields(C)[0].metadata), 4)
2098 self.assertEqual(fields(C)[0].metadata['foo'], 1)
2099 with self.assertRaises(KeyError):
2100 # Non-existent key.
2101 fields(C)[0].metadata['baz']
2102 with self.assertRaisesRegex(TypeError,
2103 'does not support item assignment'):
2104 fields(C)[0].metadata['test'] = 3
2105
2106 def test_field_metadata_custom_mapping(self):
2107 # Try a custom mapping.
2108 class SimpleNameSpace:
2109 def __init__(self, **kw):
2110 self.__dict__.update(kw)
2111
2112 def __getitem__(self, item):
2113 if item == 'xyzzy':
2114 return 'plugh'
2115 return getattr(self, item)
2116
2117 def __len__(self):
2118 return self.__dict__.__len__()
2119
2120 @dataclass
2121 class C:
2122 i: int = field(metadata=SimpleNameSpace(a=10))
2123
2124 self.assertEqual(len(fields(C)[0].metadata), 1)
2125 self.assertEqual(fields(C)[0].metadata['a'], 10)
2126 with self.assertRaises(AttributeError):
2127 fields(C)[0].metadata['b']
2128 # Make sure we're still talking to our custom mapping.
2129 self.assertEqual(fields(C)[0].metadata['xyzzy'], 'plugh')
2130
2131 def test_generic_dataclasses(self):
2132 T = TypeVar('T')
2133
2134 @dataclass
2135 class LabeledBox(Generic[T]):
2136 content: T
2137 label: str = '<unknown>'
2138
2139 box = LabeledBox(42)
2140 self.assertEqual(box.content, 42)
2141 self.assertEqual(box.label, '<unknown>')
2142
2143 # Subscripting the resulting class should work, etc.
2144 Alias = List[LabeledBox[int]]
2145
2146 def test_generic_extending(self):
2147 S = TypeVar('S')
2148 T = TypeVar('T')
2149
2150 @dataclass
2151 class Base(Generic[T, S]):
2152 x: T
2153 y: S
2154
2155 @dataclass
2156 class DataDerived(Base[int, T]):
2157 new_field: str
2158 Alias = DataDerived[str]
2159 c = Alias(0, 'test1', 'test2')
2160 self.assertEqual(astuple(c), (0, 'test1', 'test2'))
2161
2162 class NonDataDerived(Base[int, T]):
2163 def new_method(self):
2164 return self.y
2165 Alias = NonDataDerived[float]
2166 c = Alias(10, 1.0)
2167 self.assertEqual(c.new_method(), 1.0)
2168
2169 def test_generic_dynamic(self):
2170 T = TypeVar('T')
2171
2172 @dataclass
2173 class Parent(Generic[T]):
2174 x: T
2175 Child = make_dataclass('Child', [('y', T), ('z', Optional[T], None)],
2176 bases=(Parent[int], Generic[T]), namespace={'other': 42})
2177 self.assertIs(Child[int](1, 2).z, None)
2178 self.assertEqual(Child[int](1, 2, 3).z, 3)
2179 self.assertEqual(Child[int](1, 2, 3).other, 42)
2180 # Check that type aliases work correctly.
2181 Alias = Child[T]
2182 self.assertEqual(Alias[int](1, 2).x, 1)
2183 # Check MRO resolution.
2184 self.assertEqual(Child.__mro__, (Child, Parent, Generic, object))
2185
2186 def test_dataclasses_pickleable(self):
2187 global P, Q, R
2188 @dataclass
2189 class P:
2190 x: int
2191 y: int = 0
2192 @dataclass
2193 class Q:
2194 x: int
2195 y: int = field(default=0, init=False)
2196 @dataclass
2197 class R:
2198 x: int
2199 y: List[int] = field(default_factory=list)
2200 q = Q(1)
2201 q.y = 2
2202 samples = [P(1), P(1, 2), Q(1), q, R(1), R(1, [2, 3, 4])]
2203 for sample in samples:
2204 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2205 with self.subTest(sample=sample, proto=proto):
2206 new_sample = pickle.loads(pickle.dumps(sample, proto))
2207 self.assertEqual(sample.x, new_sample.x)
2208 self.assertEqual(sample.y, new_sample.y)
2209 self.assertIsNot(sample, new_sample)
2210 new_sample.x = 42
2211 another_new_sample = pickle.loads(pickle.dumps(new_sample, proto))
2212 self.assertEqual(new_sample.x, another_new_sample.x)
2213 self.assertEqual(sample.y, another_new_sample.y)
2214
2215 def test_dataclasses_qualnames(self):
2216 @dataclass(order=True, unsafe_hash=True, frozen=True)
2217 class A:
2218 x: int
2219 y: int
2220
2221 self.assertEqual(A.__init__.__name__, "__init__")
2222 for function in (
2223 '__eq__',
2224 '__lt__',
2225 '__le__',
2226 '__gt__',
2227 '__ge__',
2228 '__hash__',
2229 '__init__',
2230 '__repr__',
2231 '__setattr__',
2232 '__delattr__',
2233 ):
2234 self.assertEqual(getattr(A, function).__qualname__, f"TestCase.test_dataclasses_qualnames.<locals>.A.{function}")
2235
2236 with self.assertRaisesRegex(TypeError, r"A\.__init__\(\) missing"):
2237 A()
2238
2239
2240 class TestFieldNoAnnotation(unittest.TestCase):
2241 def test_field_without_annotation(self):
2242 with self.assertRaisesRegex(TypeError,
2243 "'f' is a field but has no type annotation"):
2244 @dataclass
2245 class C:
2246 f = field()
2247
2248 def test_field_without_annotation_but_annotation_in_base(self):
2249 @dataclass
2250 class B:
2251 f: int
2252
2253 with self.assertRaisesRegex(TypeError,
2254 "'f' is a field but has no type annotation"):
2255 # This is still an error: make sure we don't pick up the
2256 # type annotation in the base class.
2257 @dataclass
2258 class C(B):
2259 f = field()
2260
2261 def test_field_without_annotation_but_annotation_in_base_not_dataclass(self):
2262 # Same test, but with the base class not a dataclass.
2263 class B:
2264 f: int
2265
2266 with self.assertRaisesRegex(TypeError,
2267 "'f' is a field but has no type annotation"):
2268 # This is still an error: make sure we don't pick up the
2269 # type annotation in the base class.
2270 @dataclass
2271 class C(B):
2272 f = field()
2273
2274
2275 class TestDocString(unittest.TestCase):
2276 def assertDocStrEqual(self, a, b):
2277 # Because 3.6 and 3.7 differ in how inspect.signature work
2278 # (see bpo #32108), for the time being just compare them with
2279 # whitespace stripped.
2280 self.assertEqual(a.replace(' ', ''), b.replace(' ', ''))
2281
2282 @support.requires_docstrings
2283 def test_existing_docstring_not_overridden(self):
2284 @dataclass
2285 class C:
2286 """Lorem ipsum"""
2287 x: int
2288
2289 self.assertEqual(C.__doc__, "Lorem ipsum")
2290
2291 def test_docstring_no_fields(self):
2292 @dataclass
2293 class C:
2294 pass
2295
2296 self.assertDocStrEqual(C.__doc__, "C()")
2297
2298 def test_docstring_one_field(self):
2299 @dataclass
2300 class C:
2301 x: int
2302
2303 self.assertDocStrEqual(C.__doc__, "C(x:int)")
2304
2305 def test_docstring_two_fields(self):
2306 @dataclass
2307 class C:
2308 x: int
2309 y: int
2310
2311 self.assertDocStrEqual(C.__doc__, "C(x:int, y:int)")
2312
2313 def test_docstring_three_fields(self):
2314 @dataclass
2315 class C:
2316 x: int
2317 y: int
2318 z: str
2319
2320 self.assertDocStrEqual(C.__doc__, "C(x:int, y:int, z:str)")
2321
2322 def test_docstring_one_field_with_default(self):
2323 @dataclass
2324 class C:
2325 x: int = 3
2326
2327 self.assertDocStrEqual(C.__doc__, "C(x:int=3)")
2328
2329 def test_docstring_one_field_with_default_none(self):
2330 @dataclass
2331 class C:
2332 x: Union[int, type(None)] = None
2333
2334 self.assertDocStrEqual(C.__doc__, "C(x:int|None=None)")
2335
2336 def test_docstring_list_field(self):
2337 @dataclass
2338 class C:
2339 x: List[int]
2340
2341 self.assertDocStrEqual(C.__doc__, "C(x:List[int])")
2342
2343 def test_docstring_list_field_with_default_factory(self):
2344 @dataclass
2345 class C:
2346 x: List[int] = field(default_factory=list)
2347
2348 self.assertDocStrEqual(C.__doc__, "C(x:List[int]=<factory>)")
2349
2350 def test_docstring_deque_field(self):
2351 @dataclass
2352 class C:
2353 x: deque
2354
2355 self.assertDocStrEqual(C.__doc__, "C(x:collections.deque)")
2356
2357 def test_docstring_deque_field_with_default_factory(self):
2358 @dataclass
2359 class C:
2360 x: deque = field(default_factory=deque)
2361
2362 self.assertDocStrEqual(C.__doc__, "C(x:collections.deque=<factory>)")
2363
2364 def test_docstring_undefined_name(self):
2365 @dataclass
2366 class C:
2367 x: undef
2368
2369 self.assertDocStrEqual(C.__doc__, "C(x:undef)")
2370
2371 def test_docstring_with_unsolvable_forward_ref_in_init(self):
2372 # See: https://github.com/python/cpython/issues/128184
2373 ns = {}
2374 exec(
2375 textwrap.dedent(
2376 """
2377 from dataclasses import dataclass
2378
2379 @dataclass
2380 class C:
2381 def __init__(self, x: X, num: int) -> None: ...
2382 """,
2383 ),
2384 ns,
2385 )
2386
2387 self.assertDocStrEqual(ns['C'].__doc__, "C(x:X,num:int)")
2388
2389 def test_docstring_with_no_signature(self):
2390 # See https://github.com/python/cpython/issues/103449
2391 class Meta(type):
2392 __call__ = dict
2393 class Base(metaclass=Meta):
2394 pass
2395
2396 @dataclass
2397 class C(Base):
2398 pass
2399
2400 self.assertDocStrEqual(C.__doc__, "C")
2401
2402
2403 class TestInit(unittest.TestCase):
2404 def test_base_has_init(self):
2405 class B:
2406 def __init__(self):
2407 self.z = 100
2408
2409 # Make sure that declaring this class doesn't raise an error.
2410 # The issue is that we can't override __init__ in our class,
2411 # but it should be okay to add __init__ to us if our base has
2412 # an __init__.
2413 @dataclass
2414 class C(B):
2415 x: int = 0
2416 c = C(10)
2417 self.assertEqual(c.x, 10)
2418 self.assertNotIn('z', vars(c))
2419
2420 # Make sure that if we don't add an init, the base __init__
2421 # gets called.
2422 @dataclass(init=False)
2423 class C(B):
2424 x: int = 10
2425 c = C()
2426 self.assertEqual(c.x, 10)
2427 self.assertEqual(c.z, 100)
2428
2429 def test_no_init(self):
2430 @dataclass(init=False)
2431 class C:
2432 i: int = 0
2433 self.assertEqual(C().i, 0)
2434
2435 @dataclass(init=False)
2436 class C:
2437 i: int = 2
2438 def __init__(self):
2439 self.i = 3
2440 self.assertEqual(C().i, 3)
2441
2442 def test_overwriting_init(self):
2443 # If the class has __init__, use it no matter the value of
2444 # init=.
2445
2446 @dataclass
2447 class C:
2448 x: int
2449 def __init__(self, x):
2450 self.x = 2 * x
2451 self.assertEqual(C(3).x, 6)
2452
2453 @dataclass(init=True)
2454 class C:
2455 x: int
2456 def __init__(self, x):
2457 self.x = 2 * x
2458 self.assertEqual(C(4).x, 8)
2459
2460 @dataclass(init=False)
2461 class C:
2462 x: int
2463 def __init__(self, x):
2464 self.x = 2 * x
2465 self.assertEqual(C(5).x, 10)
2466
2467 def test_inherit_from_protocol(self):
2468 # Dataclasses inheriting from protocol should preserve their own `__init__`.
2469 # See bpo-45081.
2470
2471 class P(Protocol):
2472 a: int
2473
2474 @dataclass
2475 class C(P):
2476 a: int
2477
2478 self.assertEqual(C(5).a, 5)
2479
2480 @dataclass
2481 class D(P):
2482 def __init__(self, a):
2483 self.a = a * 2
2484
2485 self.assertEqual(D(5).a, 10)
2486
2487
2488 class TestInitAnnotate(unittest.TestCase):
2489 # Tests for the generated __annotate__ function for __init__
2490 # See: https://github.com/python/cpython/issues/137530
2491
2492 def test_annotate_function(self):
2493 # No forward references
2494 @dataclass
2495 class A:
2496 a: int
2497
2498 value_annos = annotationlib.get_annotations(A.__init__, format=annotationlib.Format.VALUE)
2499 forwardref_annos = annotationlib.get_annotations(A.__init__, format=annotationlib.Format.FORWARDREF)
2500 string_annos = annotationlib.get_annotations(A.__init__, format=annotationlib.Format.STRING)
2501
2502 self.assertEqual(value_annos, {'a': int, 'return': None})
2503 self.assertEqual(forwardref_annos, {'a': int, 'return': None})
2504 self.assertEqual(string_annos, {'a': 'int', 'return': 'None'})
2505
2506 self.assertTrue(getattr(A.__init__.__annotate__, "__generated_by_dataclasses__"))
2507
2508 def test_annotate_function_forwardref(self):
2509 # With forward references
2510 @dataclass
2511 class B:
2512 b: undefined
2513
2514 # VALUE annotations should raise while unresolvable
2515 with self.assertRaises(NameError):
2516 _ = annotationlib.get_annotations(B.__init__, format=annotationlib.Format.VALUE)
2517
2518 forwardref_annos = annotationlib.get_annotations(B.__init__, format=annotationlib.Format.FORWARDREF)
2519 string_annos = annotationlib.get_annotations(B.__init__, format=annotationlib.Format.STRING)
2520
2521 self.assertEqual(forwardref_annos, {'b': support.EqualToForwardRef('undefined', owner=B, is_class=True), 'return': None})
2522 self.assertEqual(string_annos, {'b': 'undefined', 'return': 'None'})
2523
2524 # Now VALUE and FORWARDREF should resolve, STRING should be unchanged
2525 undefined = int
2526
2527 value_annos = annotationlib.get_annotations(B.__init__, format=annotationlib.Format.VALUE)
2528 forwardref_annos = annotationlib.get_annotations(B.__init__, format=annotationlib.Format.FORWARDREF)
2529 string_annos = annotationlib.get_annotations(B.__init__, format=annotationlib.Format.STRING)
2530
2531 self.assertEqual(value_annos, {'b': int, 'return': None})
2532 self.assertEqual(forwardref_annos, {'b': int, 'return': None})
2533 self.assertEqual(string_annos, {'b': 'undefined', 'return': 'None'})
2534
2535 def test_annotate_function_init_false(self):
2536 # Check `init=False` attributes don't get into the annotations of the __init__ function
2537 @dataclass
2538 class C:
2539 c: str = field(init=False)
2540
2541 self.assertEqual(annotationlib.get_annotations(C.__init__), {'return': None})
2542
2543 def test_annotate_function_contains_forwardref(self):
2544 # Check string annotations on objects containing a ForwardRef
2545 @dataclass
2546 class D:
2547 d: list[undefined]
2548
2549 with self.assertRaises(NameError):
2550 annotationlib.get_annotations(D.__init__)
2551
2552 self.assertEqual(
2553 annotationlib.get_annotations(D.__init__, format=annotationlib.Format.FORWARDREF),
2554 {"d": list[support.EqualToForwardRef("undefined", is_class=True, owner=D)], "return": None}
2555 )
2556
2557 self.assertEqual(
2558 annotationlib.get_annotations(D.__init__, format=annotationlib.Format.STRING),
2559 {"d": "list[undefined]", "return": "None"}
2560 )
2561
2562 # Now test when it is defined
2563 undefined = str
2564
2565 # VALUE should now resolve
2566 self.assertEqual(
2567 annotationlib.get_annotations(D.__init__),
2568 {"d": list[str], "return": None}
2569 )
2570
2571 self.assertEqual(
2572 annotationlib.get_annotations(D.__init__, format=annotationlib.Format.FORWARDREF),
2573 {"d": list[str], "return": None}
2574 )
2575
2576 self.assertEqual(
2577 annotationlib.get_annotations(D.__init__, format=annotationlib.Format.STRING),
2578 {"d": "list[undefined]", "return": "None"}
2579 )
2580
2581 def test_annotate_function_not_replaced(self):
2582 # Check that __annotate__ is not replaced on non-generated __init__ functions
2583 @dataclass(slots=True)
2584 class E:
2585 x: str
2586 def __init__(self, x: int) -> None:
2587 self.x = x
2588
2589 self.assertEqual(
2590 annotationlib.get_annotations(E.__init__), {"x": int, "return": None}
2591 )
2592
2593 self.assertFalse(hasattr(E.__init__.__annotate__, "__generated_by_dataclasses__"))
2594
2595 def test_slots_true_init_false(self):
2596 # Test that slots=True and init=False work together and
2597 # that __annotate__ is not added to __init__.
2598
2599 @dataclass(slots=True, init=False)
2600 class F:
2601 x: int
2602
2603 f = F()
2604 f.x = 10
2605 self.assertEqual(f.x, 10)
2606
2607 self.assertFalse(hasattr(F.__init__, "__annotate__"))
2608
2609 def test_init_false_forwardref(self):
2610 # Test forward references in fields not required for __init__ annotations.
2611
2612 # At the moment this raises a NameError for VALUE annotations even though the
2613 # undefined annotation is not required for the __init__ annotations.
2614 # Ideally this will be fixed but currently there is no good way to resolve this
2615
2616 @dataclass
2617 class F:
2618 not_in_init: list[undefined] = field(init=False, default=None)
2619 in_init: int
2620
2621 annos = annotationlib.get_annotations(F.__init__, format=annotationlib.Format.FORWARDREF)
2622 self.assertEqual(
2623 annos,
2624 {"in_init": int, "return": None},
2625 )
2626
2627 with self.assertRaises(NameError):
2628 annos = annotationlib.get_annotations(F.__init__) # NameError on not_in_init
2629
2630
2631 class TestRepr(unittest.TestCase):
2632 def test_repr(self):
2633 @dataclass
2634 class B:
2635 x: int
2636
2637 @dataclass
2638 class C(B):
2639 y: int = 10
2640
2641 o = C(4)
2642 self.assertEqual(repr(o), 'TestRepr.test_repr.<locals>.C(x=4, y=10)')
2643
2644 @dataclass
2645 class D(C):
2646 x: int = 20
2647 self.assertEqual(repr(D()), 'TestRepr.test_repr.<locals>.D(x=20, y=10)')
2648
2649 @dataclass
2650 class C:
2651 @dataclass
2652 class D:
2653 i: int
2654 @dataclass
2655 class E:
2656 pass
2657 self.assertEqual(repr(C.D(0)), 'TestRepr.test_repr.<locals>.C.D(i=0)')
2658 self.assertEqual(repr(C.E()), 'TestRepr.test_repr.<locals>.C.E()')
2659
2660 def test_no_repr(self):
2661 # Test a class with no __repr__ and repr=False.
2662 @dataclass(repr=False)
2663 class C:
2664 x: int
2665 self.assertIn(f'{__name__}.TestRepr.test_no_repr.<locals>.C object at',
2666 repr(C(3)))
2667
2668 # Test a class with a __repr__ and repr=False.
2669 @dataclass(repr=False)
2670 class C:
2671 x: int
2672 def __repr__(self):
2673 return 'C-class'
2674 self.assertEqual(repr(C(3)), 'C-class')
2675
2676 def test_overwriting_repr(self):
2677 # If the class has __repr__, use it no matter the value of
2678 # repr=.
2679
2680 @dataclass
2681 class C:
2682 x: int
2683 def __repr__(self):
2684 return 'x'
2685 self.assertEqual(repr(C(0)), 'x')
2686
2687 @dataclass(repr=True)
2688 class C:
2689 x: int
2690 def __repr__(self):
2691 return 'x'
2692 self.assertEqual(repr(C(0)), 'x')
2693
2694 @dataclass(repr=False)
2695 class C:
2696 x: int
2697 def __repr__(self):
2698 return 'x'
2699 self.assertEqual(repr(C(0)), 'x')
2700
2701
2702 class TestEq(unittest.TestCase):
2703 def test_recursive_eq(self):
2704 # Test a class with recursive child
2705 @dataclass
2706 class C:
2707 recursive: object = ...
2708 c = C()
2709 c.recursive = c
2710 self.assertEqual(c, c)
2711
2712 def test_no_eq(self):
2713 # Test a class with no __eq__ and eq=False.
2714 @dataclass(eq=False)
2715 class C:
2716 x: int
2717 self.assertNotEqual(C(0), C(0))
2718 c = C(3)
2719 self.assertEqual(c, c)
2720
2721 # Test a class with an __eq__ and eq=False.
2722 @dataclass(eq=False)
2723 class C:
2724 x: int
2725 def __eq__(self, other):
2726 return other == 10
2727 self.assertEqual(C(3), 10)
2728
2729 def test_overwriting_eq(self):
2730 # If the class has __eq__, use it no matter the value of
2731 # eq=.
2732
2733 @dataclass
2734 class C:
2735 x: int
2736 def __eq__(self, other):
2737 return other == 3
2738 self.assertEqual(C(1), 3)
2739 self.assertNotEqual(C(1), 1)
2740
2741 @dataclass(eq=True)
2742 class C:
2743 x: int
2744 def __eq__(self, other):
2745 return other == 4
2746 self.assertEqual(C(1), 4)
2747 self.assertNotEqual(C(1), 1)
2748
2749 @dataclass(eq=False)
2750 class C:
2751 x: int
2752 def __eq__(self, other):
2753 return other == 5
2754 self.assertEqual(C(1), 5)
2755 self.assertNotEqual(C(1), 1)
2756
2757
2758 class TestOrdering(unittest.TestCase):
2759 def test_functools_total_ordering(self):
2760 # Test that functools.total_ordering works with this class.
2761 @total_ordering
2762 @dataclass
2763 class C:
2764 x: int
2765 def __lt__(self, other):
2766 # Perform the test "backward", just to make
2767 # sure this is being called.
2768 return self.x >= other
2769
2770 self.assertLess(C(0), -1)
2771 self.assertLessEqual(C(0), -1)
2772 self.assertGreater(C(0), 1)
2773 self.assertGreaterEqual(C(0), 1)
2774
2775 def test_no_order(self):
2776 # Test that no ordering functions are added by default.
2777 @dataclass(order=False)
2778 class C:
2779 x: int
2780 # Make sure no order methods are added.
2781 self.assertNotIn('__le__', C.__dict__)
2782 self.assertNotIn('__lt__', C.__dict__)
2783 self.assertNotIn('__ge__', C.__dict__)
2784 self.assertNotIn('__gt__', C.__dict__)
2785
2786 # Test that __lt__ is still called
2787 @dataclass(order=False)
2788 class C:
2789 x: int
2790 def __lt__(self, other):
2791 return False
2792 # Make sure other methods aren't added.
2793 self.assertNotIn('__le__', C.__dict__)
2794 self.assertNotIn('__ge__', C.__dict__)
2795 self.assertNotIn('__gt__', C.__dict__)
2796
2797 def test_overwriting_order(self):
2798 with self.assertRaisesRegex(TypeError,
2799 'Cannot overwrite attribute __lt__'
2800 '.*using functools.total_ordering'):
2801 @dataclass(order=True)
2802 class C:
2803 x: int
2804 def __lt__(self):
2805 pass
2806
2807 with self.assertRaisesRegex(TypeError,
2808 'Cannot overwrite attribute __le__'
2809 '.*using functools.total_ordering'):
2810 @dataclass(order=True)
2811 class C:
2812 x: int
2813 def __le__(self):
2814 pass
2815
2816 with self.assertRaisesRegex(TypeError,
2817 'Cannot overwrite attribute __gt__'
2818 '.*using functools.total_ordering'):
2819 @dataclass(order=True)
2820 class C:
2821 x: int
2822 def __gt__(self):
2823 pass
2824
2825 with self.assertRaisesRegex(TypeError,
2826 'Cannot overwrite attribute __ge__'
2827 '.*using functools.total_ordering'):
2828 @dataclass(order=True)
2829 class C:
2830 x: int
2831 def __ge__(self):
2832 pass
2833
2834 class TestHash(unittest.TestCase):
2835 def test_unsafe_hash(self):
2836 @dataclass(unsafe_hash=True)
2837 class C:
2838 x: int
2839 y: str
2840 self.assertEqual(hash(C(1, 'foo')), hash((1, 'foo')))
2841
2842 def test_hash_rules(self):
2843 def non_bool(value):
2844 # Map to something else that's True, but not a bool.
2845 if value is None:
2846 return None
2847 if value:
2848 return (3,)
2849 return 0
2850
2851 def test(case, unsafe_hash, eq, frozen, with_hash, result):
2852 with self.subTest(case=case, unsafe_hash=unsafe_hash, eq=eq,
2853 frozen=frozen):
2854 if result != 'exception':
2855 if with_hash:
2856 @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)
2857 class C:
2858 def __hash__(self):
2859 return 0
2860 else:
2861 @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)
2862 class C:
2863 pass
2864
2865 # See if the result matches what's expected.
2866 if result == 'fn':
2867 # __hash__ contains the function we generated.
2868 self.assertIn('__hash__', C.__dict__)
2869 self.assertIsNotNone(C.__dict__['__hash__'])
2870
2871 elif result == '':
2872 # __hash__ is not present in our class.
2873 if not with_hash:
2874 self.assertNotIn('__hash__', C.__dict__)
2875
2876 elif result == 'none':
2877 # __hash__ is set to None.
2878 self.assertIn('__hash__', C.__dict__)
2879 self.assertIsNone(C.__dict__['__hash__'])
2880
2881 elif result == 'exception':
2882 # Creating the class should cause an exception.
2883 # This only happens with with_hash==True.
2884 assert(with_hash)
2885 with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __hash__'):
2886 @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)
2887 class C:
2888 def __hash__(self):
2889 return 0
2890
2891 else:
2892 assert False, f'unknown result {result!r}'
2893
2894 # There are 8 cases of:
2895 # unsafe_hash=True/False
2896 # eq=True/False
2897 # frozen=True/False
2898 # And for each of these, a different result if
2899 # __hash__ is defined or not.
2900 for case, (unsafe_hash, eq, frozen, res_no_defined_hash, res_defined_hash) in enumerate([
2901 (False, False, False, '', ''),
2902 (False, False, True, '', ''),
2903 (False, True, False, 'none', ''),
2904 (False, True, True, 'fn', ''),
2905 (True, False, False, 'fn', 'exception'),
2906 (True, False, True, 'fn', 'exception'),
2907 (True, True, False, 'fn', 'exception'),
2908 (True, True, True, 'fn', 'exception'),
2909 ], 1):
2910 test(case, unsafe_hash, eq, frozen, False, res_no_defined_hash)
2911 test(case, unsafe_hash, eq, frozen, True, res_defined_hash)
2912
2913 # Test non-bool truth values, too. This is just to
2914 # make sure the data-driven table in the decorator
2915 # handles non-bool values.
2916 test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), False, res_no_defined_hash)
2917 test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), True, res_defined_hash)
2918
2919
2920 def test_eq_only(self):
2921 # If a class defines __eq__, __hash__ is automatically added
2922 # and set to None. This is normal Python behavior, not
2923 # related to dataclasses. Make sure we don't interfere with
2924 # that (see bpo=32546).
2925
2926 @dataclass
2927 class C:
2928 i: int
2929 def __eq__(self, other):
2930 return self.i == other.i
2931 self.assertEqual(C(1), C(1))
2932 self.assertNotEqual(C(1), C(4))
2933
2934 # And make sure things work in this case if we specify
2935 # unsafe_hash=True.
2936 @dataclass(unsafe_hash=True)
2937 class C:
2938 i: int
2939 def __eq__(self, other):
2940 return self.i == other.i
2941 self.assertEqual(C(1), C(1.0))
2942 self.assertEqual(hash(C(1)), hash(C(1.0)))
2943
2944 # And check that the classes __eq__ is being used, despite
2945 # specifying eq=True.
2946 @dataclass(unsafe_hash=True, eq=True)
2947 class C:
2948 i: int
2949 def __eq__(self, other):
2950 return self.i == 3 and self.i == other.i
2951 self.assertEqual(C(3), C(3))
2952 self.assertNotEqual(C(1), C(1))
2953 self.assertEqual(hash(C(1)), hash(C(1.0)))
2954
2955 def test_0_field_hash(self):
2956 @dataclass(frozen=True)
2957 class C:
2958 pass
2959 self.assertEqual(hash(C()), hash(()))
2960
2961 @dataclass(unsafe_hash=True)
2962 class C:
2963 pass
2964 self.assertEqual(hash(C()), hash(()))
2965
2966 def test_1_field_hash(self):
2967 @dataclass(frozen=True)
2968 class C:
2969 x: int
2970 self.assertEqual(hash(C(4)), hash((4,)))
2971 self.assertEqual(hash(C(42)), hash((42,)))
2972
2973 @dataclass(unsafe_hash=True)
2974 class C:
2975 x: int
2976 self.assertEqual(hash(C(4)), hash((4,)))
2977 self.assertEqual(hash(C(42)), hash((42,)))
2978
2979 def test_hash_no_args(self):
2980 # Test dataclasses with no hash= argument. This exists to
2981 # make sure that if the @dataclass parameter name is changed
2982 # or the non-default hashing behavior changes, the default
2983 # hashability keeps working the same way.
2984
2985 class Base:
2986 def __hash__(self):
2987 return 301
2988
2989 # If frozen or eq is None, then use the default value (do not
2990 # specify any value in the decorator).
2991 for frozen, eq, base, expected in [
2992 (None, None, object, 'unhashable'),
2993 (None, None, Base, 'unhashable'),
2994 (None, False, object, 'object'),
2995 (None, False, Base, 'base'),
2996 (None, True, object, 'unhashable'),
2997 (None, True, Base, 'unhashable'),
2998 (False, None, object, 'unhashable'),
2999 (False, None, Base, 'unhashable'),
3000 (False, False, object, 'object'),
3001 (False, False, Base, 'base'),
3002 (False, True, object, 'unhashable'),
3003 (False, True, Base, 'unhashable'),
3004 (True, None, object, 'tuple'),
3005 (True, None, Base, 'tuple'),
3006 (True, False, object, 'object'),
3007 (True, False, Base, 'base'),
3008 (True, True, object, 'tuple'),
3009 (True, True, Base, 'tuple'),
3010 ]:
3011
3012 with self.subTest(frozen=frozen, eq=eq, base=base, expected=expected):
3013 # First, create the class.
3014 if frozen is None and eq is None:
3015 @dataclass
3016 class C(base):
3017 i: int
3018 elif frozen is None:
3019 @dataclass(eq=eq)
3020 class C(base):
3021 i: int
3022 elif eq is None:
3023 @dataclass(frozen=frozen)
3024 class C(base):
3025 i: int
3026 else:
3027 @dataclass(frozen=frozen, eq=eq)
3028 class C(base):
3029 i: int
3030
3031 # Now, make sure it hashes as expected.
3032 if expected == 'unhashable':
3033 c = C(10)
3034 with self.assertRaisesRegex(TypeError, 'unhashable type'):
3035 hash(c)
3036
3037 elif expected == 'base':
3038 self.assertEqual(hash(C(10)), 301)
3039
3040 elif expected == 'object':
3041 # I'm not sure what test to use here. object's
3042 # hash isn't based on id(), so calling hash()
3043 # won't tell us much. So, just check the
3044 # function used is object's.
3045 self.assertIs(C.__hash__, object.__hash__)
3046
3047 elif expected == 'tuple':
3048 self.assertEqual(hash(C(42)), hash((42,)))
3049
3050 else:
3051 assert False, f'unknown value for expected={expected!r}'
3052
3053
3054 class TestFrozen(unittest.TestCase):
3055 # Some tests have a subtest with a slotted dataclass.
3056 # See https://github.com/python/cpython/issues/105936 for the reasons.
3057
3058 def test_frozen(self):
3059 for slots in (False, True):
3060 with self.subTest(slots=slots):
3061
3062 @dataclass(frozen=True, slots=slots)
3063 class C:
3064 i: int
3065
3066 c = C(10)
3067 self.assertEqual(c.i, 10)
3068 with self.assertRaises(FrozenInstanceError):
3069 c.i = 5
3070 self.assertEqual(c.i, 10)
3071 with self.assertRaises(FrozenInstanceError):
3072 del c.i
3073 self.assertEqual(c.i, 10)
3074
3075 def test_frozen_empty(self):
3076 for slots in (False, True):
3077 with self.subTest(slots=slots):
3078
3079 @dataclass(frozen=True, slots=slots)
3080 class C:
3081 pass
3082
3083 c = C()
3084 self.assertNotHasAttr(c, 'i')
3085 with self.assertRaises(FrozenInstanceError):
3086 c.i = 5
3087 self.assertNotHasAttr(c, 'i')
3088 with self.assertRaises(FrozenInstanceError):
3089 del c.i
3090
3091 def test_inherit(self):
3092 @dataclass(frozen=True)
3093 class C:
3094 i: int
3095
3096 @dataclass(frozen=True)
3097 class D(C):
3098 j: int
3099
3100 d = D(0, 10)
3101 with self.assertRaises(FrozenInstanceError):
3102 d.i = 5
3103 with self.assertRaises(FrozenInstanceError):
3104 d.j = 6
3105 self.assertEqual(d.i, 0)
3106 self.assertEqual(d.j, 10)
3107
3108 def test_inherit_nonfrozen_from_empty_frozen(self):
3109 @dataclass(frozen=True)
3110 class C:
3111 pass
3112
3113 with self.assertRaisesRegex(TypeError,
3114 'cannot inherit non-frozen dataclass from a frozen one'):
3115 @dataclass
3116 class D(C):
3117 j: int
3118
3119 def test_inherit_frozen_mutliple_inheritance(self):
3120 @dataclass
3121 class NotFrozen:
3122 pass
3123
3124 @dataclass(frozen=True)
3125 class Frozen:
3126 pass
3127
3128 class NotDataclass:
3129 pass
3130
3131 for bases in (
3132 (NotFrozen, Frozen),
3133 (Frozen, NotFrozen),
3134 (Frozen, NotDataclass),
3135 (NotDataclass, Frozen),
3136 ):
3137 with self.subTest(bases=bases):
3138 with self.assertRaisesRegex(
3139 TypeError,
3140 'cannot inherit non-frozen dataclass from a frozen one',
3141 ):
3142 @dataclass
3143 class NotFrozenChild(*bases):
3144 pass
3145
3146 for bases in (
3147 (NotFrozen, Frozen),
3148 (Frozen, NotFrozen),
3149 (NotFrozen, NotDataclass),
3150 (NotDataclass, NotFrozen),
3151 ):
3152 with self.subTest(bases=bases):
3153 with self.assertRaisesRegex(
3154 TypeError,
3155 'cannot inherit frozen dataclass from a non-frozen one',
3156 ):
3157 @dataclass(frozen=True)
3158 class FrozenChild(*bases):
3159 pass
3160
3161 def test_inherit_frozen_mutliple_inheritance_regular_mixins(self):
3162 @dataclass(frozen=True)
3163 class Frozen:
3164 pass
3165
3166 class NotDataclass:
3167 pass
3168
3169 class C1(Frozen, NotDataclass):
3170 pass
3171 self.assertEqual(C1.__mro__, (C1, Frozen, NotDataclass, object))
3172
3173 class C2(NotDataclass, Frozen):
3174 pass
3175 self.assertEqual(C2.__mro__, (C2, NotDataclass, Frozen, object))
3176
3177 @dataclass(frozen=True)
3178 class C3(Frozen, NotDataclass):
3179 pass
3180 self.assertEqual(C3.__mro__, (C3, Frozen, NotDataclass, object))
3181
3182 @dataclass(frozen=True)
3183 class C4(NotDataclass, Frozen):
3184 pass
3185 self.assertEqual(C4.__mro__, (C4, NotDataclass, Frozen, object))
3186
3187 def test_multiple_frozen_dataclasses_inheritance(self):
3188 @dataclass(frozen=True)
3189 class FrozenA:
3190 pass
3191
3192 @dataclass(frozen=True)
3193 class FrozenB:
3194 pass
3195
3196 class C1(FrozenA, FrozenB):
3197 pass
3198 self.assertEqual(C1.__mro__, (C1, FrozenA, FrozenB, object))
3199
3200 class C2(FrozenB, FrozenA):
3201 pass
3202 self.assertEqual(C2.__mro__, (C2, FrozenB, FrozenA, object))
3203
3204 @dataclass(frozen=True)
3205 class C3(FrozenA, FrozenB):
3206 pass
3207 self.assertEqual(C3.__mro__, (C3, FrozenA, FrozenB, object))
3208
3209 @dataclass(frozen=True)
3210 class C4(FrozenB, FrozenA):
3211 pass
3212 self.assertEqual(C4.__mro__, (C4, FrozenB, FrozenA, object))
3213
3214 def test_inherit_nonfrozen_from_empty(self):
3215 @dataclass
3216 class C:
3217 pass
3218
3219 @dataclass
3220 class D(C):
3221 j: int
3222
3223 d = D(3)
3224 self.assertEqual(d.j, 3)
3225 self.assertIsInstance(d, C)
3226
3227 # Test both ways: with an intermediate normal (non-dataclass)
3228 # class and without an intermediate class.
3229 def test_inherit_nonfrozen_from_frozen(self):
3230 for intermediate_class in [True, False]:
3231 with self.subTest(intermediate_class=intermediate_class):
3232 @dataclass(frozen=True)
3233 class C:
3234 i: int
3235
3236 if intermediate_class:
3237 class I(C): pass
3238 else:
3239 I = C
3240
3241 with self.assertRaisesRegex(TypeError,
3242 'cannot inherit non-frozen dataclass from a frozen one'):
3243 @dataclass
3244 class D(I):
3245 pass
3246
3247 def test_inherit_frozen_from_nonfrozen(self):
3248 for intermediate_class in [True, False]:
3249 with self.subTest(intermediate_class=intermediate_class):
3250 @dataclass
3251 class C:
3252 i: int
3253
3254 if intermediate_class:
3255 class I(C): pass
3256 else:
3257 I = C
3258
3259 with self.assertRaisesRegex(TypeError,
3260 'cannot inherit frozen dataclass from a non-frozen one'):
3261 @dataclass(frozen=True)
3262 class D(I):
3263 pass
3264
3265 def test_inherit_from_normal_class(self):
3266 for intermediate_class in [True, False]:
3267 with self.subTest(intermediate_class=intermediate_class):
3268 class C:
3269 pass
3270
3271 if intermediate_class:
3272 class I(C): pass
3273 else:
3274 I = C
3275
3276 @dataclass(frozen=True)
3277 class D(I):
3278 i: int
3279
3280 d = D(10)
3281 with self.assertRaises(FrozenInstanceError):
3282 d.i = 5
3283
3284 def test_non_frozen_normal_derived(self):
3285 # See bpo-32953 and https://github.com/python/cpython/issues/105936
3286 for slots in (False, True):
3287 with self.subTest(slots=slots):
3288
3289 @dataclass(frozen=True, slots=slots)
3290 class D:
3291 x: int
3292 y: int = 10
3293
3294 class S(D):
3295 pass
3296
3297 s = S(3)
3298 self.assertEqual(s.x, 3)
3299 self.assertEqual(s.y, 10)
3300 s.cached = True
3301
3302 # But can't change the frozen attributes.
3303 with self.assertRaises(FrozenInstanceError):
3304 s.x = 5
3305 with self.assertRaises(FrozenInstanceError):
3306 s.y = 5
3307 self.assertEqual(s.x, 3)
3308 self.assertEqual(s.y, 10)
3309 self.assertEqual(s.cached, True)
3310
3311 with self.assertRaises(FrozenInstanceError):
3312 del s.x
3313 self.assertEqual(s.x, 3)
3314 with self.assertRaises(FrozenInstanceError):
3315 del s.y
3316 self.assertEqual(s.y, 10)
3317 del s.cached
3318 self.assertNotHasAttr(s, 'cached')
3319 with self.assertRaises(AttributeError) as cm:
3320 del s.cached
3321 self.assertNotIsInstance(cm.exception, FrozenInstanceError)
3322
3323 def test_non_frozen_normal_derived_from_empty_frozen(self):
3324 @dataclass(frozen=True)
3325 class D:
3326 pass
3327
3328 class S(D):
3329 pass
3330
3331 s = S()
3332 self.assertNotHasAttr(s, 'x')
3333 s.x = 5
3334 self.assertEqual(s.x, 5)
3335
3336 del s.x
3337 self.assertNotHasAttr(s, 'x')
3338 with self.assertRaises(AttributeError) as cm:
3339 del s.x
3340 self.assertNotIsInstance(cm.exception, FrozenInstanceError)
3341
3342 def test_overwriting_frozen(self):
3343 # frozen uses __setattr__ and __delattr__.
3344 with self.assertRaisesRegex(TypeError,
3345 'Cannot overwrite attribute __setattr__'):
3346 @dataclass(frozen=True)
3347 class C:
3348 x: int
3349 def __setattr__(self):
3350 pass
3351
3352 with self.assertRaisesRegex(TypeError,
3353 'Cannot overwrite attribute __delattr__'):
3354 @dataclass(frozen=True)
3355 class C:
3356 x: int
3357 def __delattr__(self):
3358 pass
3359
3360 @dataclass(frozen=False)
3361 class C:
3362 x: int
3363 def __setattr__(self, name, value):
3364 self.__dict__['x'] = value * 2
3365 self.assertEqual(C(10).x, 20)
3366
3367 def test_frozen_hash(self):
3368 @dataclass(frozen=True)
3369 class C:
3370 x: Any
3371
3372 # If x is immutable, we can compute the hash. No exception is
3373 # raised.
3374 hash(C(3))
3375
3376 # If x is mutable, computing the hash is an error.
3377 with self.assertRaisesRegex(TypeError, 'unhashable type'):
3378 hash(C({}))
3379
3380 def test_frozen_deepcopy_without_slots(self):
3381 # see: https://github.com/python/cpython/issues/89683
3382 @dataclass(frozen=True, slots=False)
3383 class C:
3384 s: str
3385
3386 c = C('hello')
3387 self.assertEqual(deepcopy(c), c)
3388
3389 def test_frozen_deepcopy_with_slots(self):
3390 # see: https://github.com/python/cpython/issues/89683
3391 with self.subTest('generated __slots__'):
3392 @dataclass(frozen=True, slots=True)
3393 class C:
3394 s: str
3395
3396 c = C('hello')
3397 self.assertEqual(deepcopy(c), c)
3398
3399 with self.subTest('user-defined __slots__ and no __{get,set}state__'):
3400 @dataclass(frozen=True, slots=False)
3401 class C:
3402 __slots__ = ('s',)
3403 s: str
3404
3405 # with user-defined slots, __getstate__ and __setstate__ are not
3406 # automatically added, hence the error
3407 err = r"^cannot\ assign\ to\ field\ 's'$"
3408 self.assertRaisesRegex(FrozenInstanceError, err, deepcopy, C(''))
3409
3410 with self.subTest('user-defined __slots__ and __{get,set}state__'):
3411 @dataclass(frozen=True, slots=False)
3412 class C:
3413 __slots__ = ('s',)
3414 __getstate__ = dataclasses._dataclass_getstate
3415 __setstate__ = dataclasses._dataclass_setstate
3416
3417 s: str
3418
3419 c = C('hello')
3420 self.assertEqual(deepcopy(c), c)
3421
3422
3423 class TestSlots(unittest.TestCase):
3424 def test_simple(self):
3425 @dataclass
3426 class C:
3427 __slots__ = ('x',)
3428 x: Any
3429
3430 # There was a bug where a variable in a slot was assumed to
3431 # also have a default value (of type
3432 # types.MemberDescriptorType).
3433 with self.assertRaisesRegex(TypeError,
3434 r"__init__\(\) missing 1 required positional argument: 'x'"):
3435 C()
3436
3437 # We can create an instance, and assign to x.
3438 c = C(10)
3439 self.assertEqual(c.x, 10)
3440 c.x = 5
3441 self.assertEqual(c.x, 5)
3442
3443 # We can't assign to anything else.
3444 with self.assertRaisesRegex(AttributeError, "'C' object has no attribute 'y'"):
3445 c.y = 5
3446
3447 def test_derived_added_field(self):
3448 # See bpo-33100.
3449 @dataclass
3450 class Base:
3451 __slots__ = ('x',)
3452 x: Any
3453
3454 @dataclass
3455 class Derived(Base):
3456 x: int
3457 y: int
3458
3459 d = Derived(1, 2)
3460 self.assertEqual((d.x, d.y), (1, 2))
3461
3462 # We can add a new field to the derived instance.
3463 d.z = 10
3464
3465 def test_generated_slots(self):
3466 @dataclass(slots=True)
3467 class C:
3468 x: int
3469 y: int
3470
3471 c = C(1, 2)
3472 self.assertEqual((c.x, c.y), (1, 2))
3473
3474 c.x = 3
3475 c.y = 4
3476 self.assertEqual((c.x, c.y), (3, 4))
3477
3478 with self.assertRaisesRegex(AttributeError, "'C' object has no attribute 'z'"):
3479 c.z = 5
3480
3481 def test_add_slots_when_slots_exists(self):
3482 with self.assertRaisesRegex(TypeError, '^C already specifies __slots__$'):
3483 @dataclass(slots=True)
3484 class C:
3485 __slots__ = ('x',)
3486 x: int
3487
3488 def test_generated_slots_value(self):
3489
3490 class Root:
3491 __slots__ = {'x'}
3492
3493 class Root2(Root):
3494 __slots__ = {'k': '...', 'j': ''}
3495
3496 class Root3(Root2):
3497 __slots__ = ['h']
3498
3499 class Root4(Root3):
3500 __slots__ = 'aa'
3501
3502 @dataclass(slots=True)
3503 class Base(Root4):
3504 y: int
3505 j: str
3506 h: str
3507
3508 self.assertEqual(Base.__slots__, ('y',))
3509
3510 @dataclass(slots=True)
3511 class Derived(Base):
3512 aa: float
3513 x: str
3514 z: int
3515 k: str
3516 h: str
3517
3518 self.assertEqual(Derived.__slots__, ('z',))
3519
3520 @dataclass
3521 class AnotherDerived(Base):
3522 z: int
3523
3524 self.assertNotIn('__slots__', AnotherDerived.__dict__)
3525
3526 def test_slots_with_docs(self):
3527 class Root:
3528 __slots__ = {'x': 'x'}
3529
3530 @dataclass(slots=True)
3531 class Base(Root):
3532 y1: int = field(doc='y1')
3533 y2: int
3534
3535 self.assertEqual(Base.__slots__, {'y1': 'y1', 'y2': None})
3536
3537 @dataclass(slots=True)
3538 class Child(Base):
3539 z1: int = field(doc='z1')
3540 z2: int
3541
3542 self.assertEqual(Child.__slots__, {'z1': 'z1', 'z2': None})
3543
3544 def test_cant_inherit_from_iterator_slots(self):
3545
3546 class Root:
3547 __slots__ = iter(['a'])
3548
3549 class Root2(Root):
3550 __slots__ = ('b', )
3551
3552 with self.assertRaisesRegex(
3553 TypeError,
3554 "^Slots of 'Root' cannot be determined"
3555 ):
3556 @dataclass(slots=True)
3557 class C(Root2):
3558 x: int
3559
3560 def test_returns_new_class(self):
3561 class A:
3562 x: int
3563
3564 B = dataclass(A, slots=True)
3565 self.assertIsNot(A, B)
3566
3567 self.assertNotHasAttr(A, "__slots__")
3568 self.assertHasAttr(B, "__slots__")
3569
3570 # Can't be local to test_frozen_pickle.
3571 @dataclass(frozen=True, slots=True)
3572 class FrozenSlotsClass:
3573 foo: str
3574 bar: int
3575
3576 @dataclass(frozen=True)
3577 class FrozenWithoutSlotsClass:
3578 foo: str
3579 bar: int
3580
3581 def test_frozen_pickle(self):
3582 # bpo-43999
3583
3584 self.assertEqual(self.FrozenSlotsClass.__slots__, ("foo", "bar"))
3585 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
3586 with self.subTest(proto=proto):
3587 obj = self.FrozenSlotsClass("a", 1)
3588 p = pickle.loads(pickle.dumps(obj, protocol=proto))
3589 self.assertIsNot(obj, p)
3590 self.assertEqual(obj, p)
3591
3592 obj = self.FrozenWithoutSlotsClass("a", 1)
3593 p = pickle.loads(pickle.dumps(obj, protocol=proto))
3594 self.assertIsNot(obj, p)
3595 self.assertEqual(obj, p)
3596
3597 @dataclass(frozen=True, slots=True)
3598 class FrozenSlotsGetStateClass:
3599 foo: str
3600 bar: int
3601
3602 getstate_called: bool = field(default=False, compare=False)
3603
3604 def __getstate__(self):
3605 object.__setattr__(self, 'getstate_called', True)
3606 return [self.foo, self.bar]
3607
3608 @dataclass(frozen=True, slots=True)
3609 class FrozenSlotsSetStateClass:
3610 foo: str
3611 bar: int
3612
3613 setstate_called: bool = field(default=False, compare=False)
3614
3615 def __setstate__(self, state):
3616 object.__setattr__(self, 'setstate_called', True)
3617 object.__setattr__(self, 'foo', state[0])
3618 object.__setattr__(self, 'bar', state[1])
3619
3620 @dataclass(frozen=True, slots=True)
3621 class FrozenSlotsAllStateClass:
3622 foo: str
3623 bar: int
3624
3625 getstate_called: bool = field(default=False, compare=False)
3626 setstate_called: bool = field(default=False, compare=False)
3627
3628 def __getstate__(self):
3629 object.__setattr__(self, 'getstate_called', True)
3630 return [self.foo, self.bar]
3631
3632 def __setstate__(self, state):
3633 object.__setattr__(self, 'setstate_called', True)
3634 object.__setattr__(self, 'foo', state[0])
3635 object.__setattr__(self, 'bar', state[1])
3636
3637 def test_frozen_slots_pickle_custom_state(self):
3638 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
3639 with self.subTest(proto=proto):
3640 obj = self.FrozenSlotsGetStateClass('a', 1)
3641 dumped = pickle.dumps(obj, protocol=proto)
3642
3643 self.assertTrue(obj.getstate_called)
3644 self.assertEqual(obj, pickle.loads(dumped))
3645
3646 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
3647 with self.subTest(proto=proto):
3648 obj = self.FrozenSlotsSetStateClass('a', 1)
3649 obj2 = pickle.loads(pickle.dumps(obj, protocol=proto))
3650
3651 self.assertTrue(obj2.setstate_called)
3652 self.assertEqual(obj, obj2)
3653
3654 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
3655 with self.subTest(proto=proto):
3656 obj = self.FrozenSlotsAllStateClass('a', 1)
3657 dumped = pickle.dumps(obj, protocol=proto)
3658
3659 self.assertTrue(obj.getstate_called)
3660
3661 obj2 = pickle.loads(dumped)
3662 self.assertTrue(obj2.setstate_called)
3663 self.assertEqual(obj, obj2)
3664
3665 def test_slots_with_default_no_init(self):
3666 # Originally reported in bpo-44649.
3667 @dataclass(slots=True)
3668 class A:
3669 a: str
3670 b: str = field(default='b', init=False)
3671
3672 obj = A("a")
3673 self.assertEqual(obj.a, 'a')
3674 self.assertEqual(obj.b, 'b')
3675
3676 def test_slots_with_default_factory_no_init(self):
3677 # Originally reported in bpo-44649.
3678 @dataclass(slots=True)
3679 class A:
3680 a: str
3681 b: str = field(default_factory=lambda:'b', init=False)
3682
3683 obj = A("a")
3684 self.assertEqual(obj.a, 'a')
3685 self.assertEqual(obj.b, 'b')
3686
3687 def test_slots_no_weakref(self):
3688 @dataclass(slots=True)
3689 class A:
3690 # No weakref.
3691 pass
3692
3693 self.assertNotIn("__weakref__", A.__slots__)
3694 a = A()
3695 with self.assertRaisesRegex(TypeError,
3696 "cannot create weak reference"):
3697 weakref.ref(a)
3698 with self.assertRaises(AttributeError):
3699 a.__weakref__
3700
3701 def test_slots_weakref(self):
3702 @dataclass(slots=True, weakref_slot=True)
3703 class A:
3704 a: int
3705
3706 self.assertIn("__weakref__", A.__slots__)
3707 a = A(1)
3708 a_ref = weakref.ref(a)
3709
3710 self.assertIs(a.__weakref__, a_ref)
3711
3712 def test_slots_weakref_base_str(self):
3713 class Base:
3714 __slots__ = '__weakref__'
3715
3716 @dataclass(slots=True)
3717 class A(Base):
3718 a: int
3719
3720 # __weakref__ is in the base class, not A. But an A is still weakref-able.
3721 self.assertIn("__weakref__", Base.__slots__)
3722 self.assertNotIn("__weakref__", A.__slots__)
3723 a = A(1)
3724 weakref.ref(a)
3725
3726 def test_slots_weakref_base_tuple(self):
3727 # Same as test_slots_weakref_base, but use a tuple instead of a string
3728 # in the base class.
3729 class Base:
3730 __slots__ = ('__weakref__',)
3731
3732 @dataclass(slots=True)
3733 class A(Base):
3734 a: int
3735
3736 # __weakref__ is in the base class, not A. But an A is still
3737 # weakref-able.
3738 self.assertIn("__weakref__", Base.__slots__)
3739 self.assertNotIn("__weakref__", A.__slots__)
3740 a = A(1)
3741 weakref.ref(a)
3742
3743 def test_weakref_slot_without_slot(self):
3744 with self.assertRaisesRegex(TypeError,
3745 "weakref_slot is True but slots is False"):
3746 @dataclass(weakref_slot=True)
3747 class A:
3748 a: int
3749
3750 def test_weakref_slot_make_dataclass(self):
3751 A = make_dataclass('A', [('a', int),], slots=True, weakref_slot=True)
3752 self.assertIn("__weakref__", A.__slots__)
3753 a = A(1)
3754 weakref.ref(a)
3755
3756 # And make sure if raises if slots=True is not given.
3757 with self.assertRaisesRegex(TypeError,
3758 "weakref_slot is True but slots is False"):
3759 B = make_dataclass('B', [('a', int),], weakref_slot=True)
3760
3761 def test_weakref_slot_subclass_weakref_slot(self):
3762 @dataclass(slots=True, weakref_slot=True)
3763 class Base:
3764 field: int
3765
3766 # A *can* also specify weakref_slot=True if it wants to (gh-93521)
3767 @dataclass(slots=True, weakref_slot=True)
3768 class A(Base):
3769 ...
3770
3771 # __weakref__ is in the base class, not A. But an instance of A
3772 # is still weakref-able.
3773 self.assertIn("__weakref__", Base.__slots__)
3774 self.assertNotIn("__weakref__", A.__slots__)
3775 a = A(1)
3776 a_ref = weakref.ref(a)
3777 self.assertIs(a.__weakref__, a_ref)
3778
3779 def test_weakref_slot_subclass_no_weakref_slot(self):
3780 @dataclass(slots=True, weakref_slot=True)
3781 class Base:
3782 field: int
3783
3784 @dataclass(slots=True)
3785 class A(Base):
3786 ...
3787
3788 # __weakref__ is in the base class, not A. Even though A doesn't
3789 # specify weakref_slot, it should still be weakref-able.
3790 self.assertIn("__weakref__", Base.__slots__)
3791 self.assertNotIn("__weakref__", A.__slots__)
3792 a = A(1)
3793 a_ref = weakref.ref(a)
3794 self.assertIs(a.__weakref__, a_ref)
3795
3796 def test_weakref_slot_normal_base_weakref_slot(self):
3797 class Base:
3798 __slots__ = ('__weakref__',)
3799
3800 @dataclass(slots=True, weakref_slot=True)
3801 class A(Base):
3802 field: int
3803
3804 # __weakref__ is in the base class, not A. But an instance of
3805 # A is still weakref-able.
3806 self.assertIn("__weakref__", Base.__slots__)
3807 self.assertNotIn("__weakref__", A.__slots__)
3808 a = A(1)
3809 a_ref = weakref.ref(a)
3810 self.assertIs(a.__weakref__, a_ref)
3811
3812 def test_dataclass_derived_weakref_slot(self):
3813 class A:
3814 pass
3815
3816 @dataclass(slots=True, weakref_slot=True)
3817 class B(A):
3818 pass
3819
3820 self.assertEqual(B.__slots__, ())
3821 B()
3822
3823 def test_dataclass_derived_generic(self):
3824 T = typing.TypeVar('T')
3825
3826 @dataclass(slots=True, weakref_slot=True)
3827 class A(typing.Generic[T]):
3828 pass
3829 self.assertEqual(A.__slots__, ('__weakref__',))
3830 self.assertTrue(A.__weakref__)
3831 A()
3832
3833 @dataclass(slots=True, weakref_slot=True)
3834 class B[T2]:
3835 pass
3836 self.assertEqual(B.__slots__, ('__weakref__',))
3837 self.assertTrue(B.__weakref__)
3838 B()
3839
3840 def test_dataclass_derived_generic_from_base(self):
3841 T = typing.TypeVar('T')
3842
3843 class RawBase: ...
3844
3845 @dataclass(slots=True, weakref_slot=True)
3846 class C1(typing.Generic[T], RawBase):
3847 pass
3848 self.assertEqual(C1.__slots__, ())
3849 self.assertTrue(C1.__weakref__)
3850 C1()
3851 @dataclass(slots=True, weakref_slot=True)
3852 class C2(RawBase, typing.Generic[T]):
3853 pass
3854 self.assertEqual(C2.__slots__, ())
3855 self.assertTrue(C2.__weakref__)
3856 C2()
3857
3858 @dataclass(slots=True, weakref_slot=True)
3859 class D[T2](RawBase):
3860 pass
3861 self.assertEqual(D.__slots__, ())
3862 self.assertTrue(D.__weakref__)
3863 D()
3864
3865 def test_dataclass_derived_generic_from_slotted_base(self):
3866 T = typing.TypeVar('T')
3867
3868 class WithSlots:
3869 __slots__ = ('a', 'b')
3870
3871 @dataclass(slots=True, weakref_slot=True)
3872 class E1(WithSlots, Generic[T]):
3873 pass
3874 self.assertEqual(E1.__slots__, ('__weakref__',))
3875 self.assertTrue(E1.__weakref__)
3876 E1()
3877 @dataclass(slots=True, weakref_slot=True)
3878 class E2(Generic[T], WithSlots):
3879 pass
3880 self.assertEqual(E2.__slots__, ('__weakref__',))
3881 self.assertTrue(E2.__weakref__)
3882 E2()
3883
3884 @dataclass(slots=True, weakref_slot=True)
3885 class F[T2](WithSlots):
3886 pass
3887 self.assertEqual(F.__slots__, ('__weakref__',))
3888 self.assertTrue(F.__weakref__)
3889 F()
3890
3891 def test_dataclass_derived_generic_from_slotted_base_with_weakref(self):
3892 T = typing.TypeVar('T')
3893
3894 class WithWeakrefSlot:
3895 __slots__ = ('__weakref__',)
3896
3897 @dataclass(slots=True, weakref_slot=True)
3898 class G1(WithWeakrefSlot, Generic[T]):
3899 pass
3900 self.assertEqual(G1.__slots__, ())
3901 self.assertTrue(G1.__weakref__)
3902 G1()
3903 @dataclass(slots=True, weakref_slot=True)
3904 class G2(Generic[T], WithWeakrefSlot):
3905 pass
3906 self.assertEqual(G2.__slots__, ())
3907 self.assertTrue(G2.__weakref__)
3908 G2()
3909
3910 @dataclass(slots=True, weakref_slot=True)
3911 class H[T2](WithWeakrefSlot):
3912 pass
3913 self.assertEqual(H.__slots__, ())
3914 self.assertTrue(H.__weakref__)
3915 H()
3916
3917 def test_dataclass_slot_dict(self):
3918 class WithDictSlot:
3919 __slots__ = ('__dict__',)
3920
3921 @dataclass(slots=True)
3922 class A(WithDictSlot): ...
3923
3924 self.assertEqual(A.__slots__, ())
3925 self.assertEqual(A().__dict__, {})
3926 A()
3927
3928 @support.cpython_only
3929 def test_dataclass_slot_dict_ctype(self):
3930 # https://github.com/python/cpython/issues/123935
3931 # Skips test if `_testcapi` is not present:
3932 _testcapi = import_helper.import_module('_testcapi')
3933
3934 @dataclass(slots=True)
3935 class HasDictOffset(_testcapi.HeapCTypeWithDict):
3936 __dict__: dict = {}
3937 self.assertNotEqual(_testcapi.HeapCTypeWithDict.__dictoffset__, 0)
3938 self.assertEqual(HasDictOffset.__slots__, ())
3939
3940 @dataclass(slots=True)
3941 class DoesNotHaveDictOffset(_testcapi.HeapCTypeWithWeakref):
3942 __dict__: dict = {}
3943 self.assertEqual(_testcapi.HeapCTypeWithWeakref.__dictoffset__, 0)
3944 self.assertEqual(DoesNotHaveDictOffset.__slots__, ('__dict__',))
3945
3946 @support.cpython_only
3947 def test_slots_with_wrong_init_subclass(self):
3948 # TODO: This test is for a kinda-buggy behavior.
3949 # Ideally, it should be fixed and `__init_subclass__`
3950 # should be fully supported in the future versions.
3951 # See https://github.com/python/cpython/issues/91126
3952 class WrongSuper:
3953 def __init_subclass__(cls, arg):
3954 pass
3955
3956 with self.assertRaisesRegex(
3957 TypeError,
3958 "missing 1 required positional argument: 'arg'",
3959 ):
3960 @dataclass(slots=True)
3961 class WithWrongSuper(WrongSuper, arg=1):
3962 pass
3963
3964 class CorrectSuper:
3965 args = []
3966 def __init_subclass__(cls, arg="default"):
3967 cls.args.append(arg)
3968
3969 @dataclass(slots=True)
3970 class WithCorrectSuper(CorrectSuper):
3971 pass
3972
3973 # __init_subclass__ is called twice: once for `WithCorrectSuper`
3974 # and once for `WithCorrectSuper__slots__` new class
3975 # that we create internally.
3976 self.assertEqual(CorrectSuper.args, ["default", "default"])
3977
3978 def test_original_class_is_gced(self):
3979 # gh-135228: Make sure when we replace the class with slots=True, the original class
3980 # gets garbage collected.
3981 def make_simple():
3982 @dataclass(slots=True)
3983 class SlotsTest:
3984 pass
3985
3986 return SlotsTest
3987
3988 # See https://github.com/python/cpython/issues/135228#issuecomment-3755979059
3989 def make_frozen():
3990 @dataclass(frozen=True, slots=True)
3991 class SlotsTest:
3992 pass
3993
3994 return SlotsTest
3995
3996 def make_with_annotations():
3997 @dataclass(slots=True)
3998 class SlotsTest:
3999 x: int
4000
4001 return SlotsTest
4002
4003 def make_with_annotations_and_method():
4004 @dataclass(slots=True)
4005 class SlotsTest:
4006 x: int
4007
4008 def method(self) -> int:
4009 return self.x
4010
4011 return SlotsTest
4012
4013 def make_with_forwardref():
4014 @dataclass(slots=True)
4015 class SlotsTest:
4016 x: undefined
4017 y: list[undefined]
4018
4019 return SlotsTest
4020
4021 for make in (make_simple, make_frozen, make_with_annotations, make_with_annotations_and_method, make_with_forwardref):
4022 with self.subTest(make=make):
4023 C = make()
4024 support.gc_collect()
4025 candidates = [cls for cls in object.__subclasses__() if cls.__name__ == 'SlotsTest'
4026 and cls.__firstlineno__ == make.__code__.co_firstlineno + 1]
4027 self.assertEqual(candidates, [C])
4028
4029
4030 class TestDescriptors(unittest.TestCase):
4031 def test_set_name(self):
4032 # See bpo-33141.
4033
4034 # Create a descriptor.
4035 class D:
4036 def __set_name__(self, owner, name):
4037 self.name = name + 'x'
4038 def __get__(self, instance, owner):
4039 if instance is not None:
4040 return 1
4041 return self
4042
4043 # This is the case of just normal descriptor behavior, no
4044 # dataclass code is involved in initializing the descriptor.
4045 @dataclass
4046 class C:
4047 c: int=D()
4048 self.assertEqual(C.c.name, 'cx')
4049
4050 # Now test with a default value and init=False, which is the
4051 # only time this is really meaningful. If not using
4052 # init=False, then the descriptor will be overwritten, anyway.
4053 @dataclass
4054 class C:
4055 c: int=field(default=D(), init=False)
4056 self.assertEqual(C.c.name, 'cx')
4057 self.assertEqual(C().c, 1)
4058
4059 def test_non_descriptor(self):
4060 # PEP 487 says __set_name__ should work on non-descriptors.
4061 # Create a descriptor.
4062
4063 class D:
4064 def __set_name__(self, owner, name):
4065 self.name = name + 'x'
4066
4067 @dataclass
4068 class C:
4069 c: int=field(default=D(), init=False)
4070 self.assertEqual(C.c.name, 'cx')
4071
4072 def test_lookup_on_instance(self):
4073 # See bpo-33175.
4074 class D:
4075 pass
4076
4077 d = D()
4078 # Create an attribute on the instance, not type.
4079 d.__set_name__ = Mock()
4080
4081 # Make sure d.__set_name__ is not called.
4082 @dataclass
4083 class C:
4084 i: int=field(default=d, init=False)
4085
4086 self.assertEqual(d.__set_name__.call_count, 0)
4087
4088 def test_lookup_on_class(self):
4089 # See bpo-33175.
4090 class D:
4091 pass
4092 D.__set_name__ = Mock()
4093
4094 # Make sure D.__set_name__ is called.
4095 @dataclass
4096 class C:
4097 i: int=field(default=D(), init=False)
4098
4099 self.assertEqual(D.__set_name__.call_count, 1)
4100
4101 def test_init_calls_set(self):
4102 class D:
4103 pass
4104
4105 D.__set__ = Mock()
4106
4107 @dataclass
4108 class C:
4109 i: D = D()
4110
4111 # Make sure D.__set__ is called.
4112 D.__set__.reset_mock()
4113 c = C(5)
4114 self.assertEqual(D.__set__.call_count, 1)
4115
4116 def test_getting_field_calls_get(self):
4117 class D:
4118 pass
4119
4120 D.__set__ = Mock()
4121 D.__get__ = Mock()
4122
4123 @dataclass
4124 class C:
4125 i: D = D()
4126
4127 c = C(5)
4128
4129 # Make sure D.__get__ is called.
4130 D.__get__.reset_mock()
4131 value = c.i
4132 self.assertEqual(D.__get__.call_count, 1)
4133
4134 def test_setting_field_calls_set(self):
4135 class D:
4136 pass
4137
4138 D.__set__ = Mock()
4139
4140 @dataclass
4141 class C:
4142 i: D = D()
4143
4144 c = C(5)
4145
4146 # Make sure D.__set__ is called.
4147 D.__set__.reset_mock()
4148 c.i = 10
4149 self.assertEqual(D.__set__.call_count, 1)
4150
4151 def test_setting_uninitialized_descriptor_field(self):
4152 class D:
4153 pass
4154
4155 D.__set__ = Mock()
4156
4157 @dataclass
4158 class C:
4159 i: D
4160
4161 # D.__set__ is not called because there's no D instance to call it on
4162 D.__set__.reset_mock()
4163 c = C(5)
4164 self.assertEqual(D.__set__.call_count, 0)
4165
4166 # D.__set__ still isn't called after setting i to an instance of D
4167 # because descriptors don't behave like that when stored as instance vars
4168 c.i = D()
4169 c.i = 5
4170 self.assertEqual(D.__set__.call_count, 0)
4171
4172 def test_default_value(self):
4173 class D:
4174 def __get__(self, instance: Any, owner: object) -> int:
4175 if instance is None:
4176 return 100
4177
4178 return instance._x
4179
4180 def __set__(self, instance: Any, value: int) -> None:
4181 instance._x = value
4182
4183 @dataclass
4184 class C:
4185 i: D = D()
4186
4187 c = C()
4188 self.assertEqual(c.i, 100)
4189
4190 c = C(5)
4191 self.assertEqual(c.i, 5)
4192
4193 def test_no_default_value(self):
4194 class D:
4195 def __get__(self, instance: Any, owner: object) -> int:
4196 if instance is None:
4197 raise AttributeError()
4198
4199 return instance._x
4200
4201 def __set__(self, instance: Any, value: int) -> None:
4202 instance._x = value
4203
4204 @dataclass
4205 class C:
4206 i: D = D()
4207
4208 with self.assertRaisesRegex(TypeError, 'missing 1 required positional argument'):
4209 c = C()
4210
4211 class TestStringAnnotations(unittest.TestCase):
4212 def test_classvar(self):
4213 # Some expressions recognized as ClassVar really aren't. But
4214 # if you're using string annotations, it's not an exact
4215 # science.
4216 # These tests assume that both "import typing" and "from
4217 # typing import *" have been run in this file.
4218 for typestr in ('ClassVar[int]',
4219 'ClassVar [int]',
4220 ' ClassVar [int]',
4221 'ClassVar',
4222 ' ClassVar ',
4223 'typing.ClassVar[int]',
4224 'typing.ClassVar[str]',
4225 ' typing.ClassVar[str]',
4226 'typing .ClassVar[str]',
4227 'typing. ClassVar[str]',
4228 'typing.ClassVar [str]',
4229 'typing.ClassVar [ str]',
4230
4231 # Not syntactically valid, but these will
4232 # be treated as ClassVars.
4233 'typing.ClassVar.[int]',
4234 'typing.ClassVar+',
4235 ):
4236 with self.subTest(typestr=typestr):
4237 @dataclass
4238 class C:
4239 x: typestr
4240
4241 # x is a ClassVar, so C() takes no args.
4242 C()
4243
4244 # And it won't appear in the class's dict because it doesn't
4245 # have a default.
4246 self.assertNotIn('x', C.__dict__)
4247
4248 def test_isnt_classvar(self):
4249 for typestr in ('CV',
4250 't.ClassVar',
4251 't.ClassVar[int]',
4252 'typing..ClassVar[int]',
4253 'Classvar',
4254 'Classvar[int]',
4255 'typing.ClassVarx[int]',
4256 'typong.ClassVar[int]',
4257 'dataclasses.ClassVar[int]',
4258 'typingxClassVar[str]',
4259 ):
4260 with self.subTest(typestr=typestr):
4261 @dataclass
4262 class C:
4263 x: typestr
4264
4265 # x is not a ClassVar, so C() takes one arg.
4266 self.assertEqual(C(10).x, 10)
4267
4268 def test_initvar(self):
4269 # These tests assume that both "import dataclasses" and "from
4270 # dataclasses import *" have been run in this file.
4271 for typestr in ('InitVar[int]',
4272 'InitVar [int]'
4273 ' InitVar [int]',
4274 'InitVar',
4275 ' InitVar ',
4276 'dataclasses.InitVar[int]',
4277 'dataclasses.InitVar[str]',
4278 ' dataclasses.InitVar[str]',
4279 'dataclasses .InitVar[str]',
4280 'dataclasses. InitVar[str]',
4281 'dataclasses.InitVar [str]',
4282 'dataclasses.InitVar [ str]',
4283
4284 # Not syntactically valid, but these will
4285 # be treated as InitVars.
4286 'dataclasses.InitVar.[int]',
4287 'dataclasses.InitVar+',
4288 ):
4289 with self.subTest(typestr=typestr):
4290 @dataclass
4291 class C:
4292 x: typestr
4293
4294 # x is an InitVar, so doesn't create a member.
4295 with self.assertRaisesRegex(AttributeError,
4296 "object has no attribute 'x'"):
4297 C(1).x
4298
4299 def test_isnt_initvar(self):
4300 for typestr in ('IV',
4301 'dc.InitVar',
4302 'xdataclasses.xInitVar',
4303 'typing.xInitVar[int]',
4304 ):
4305 with self.subTest(typestr=typestr):
4306 @dataclass
4307 class C:
4308 x: typestr
4309
4310 # x is not an InitVar, so there will be a member x.
4311 self.assertEqual(C(10).x, 10)
4312
4313 def test_classvar_module_level_import(self):
4314 from test.test_dataclasses import dataclass_module_1
4315 from test.test_dataclasses import dataclass_module_1_str
4316 from test.test_dataclasses import dataclass_module_2
4317 from test.test_dataclasses import dataclass_module_2_str
4318
4319 for m in (dataclass_module_1, dataclass_module_1_str,
4320 dataclass_module_2, dataclass_module_2_str,
4321 ):
4322 with self.subTest(m=m):
4323 # There's a difference in how the ClassVars are
4324 # interpreted when using string annotations or
4325 # not. See the imported modules for details.
4326 if m.USING_STRINGS:
4327 c = m.CV(10)
4328 else:
4329 c = m.CV()
4330 self.assertEqual(c.cv0, 20)
4331
4332
4333 # There's a difference in how the InitVars are
4334 # interpreted when using string annotations or
4335 # not. See the imported modules for details.
4336 c = m.IV(0, 1, 2, 3, 4)
4337
4338 for field_name in ('iv0', 'iv1', 'iv2', 'iv3'):
4339 with self.subTest(field_name=field_name):
4340 with self.assertRaisesRegex(AttributeError, f"object has no attribute '{field_name}'"):
4341 # Since field_name is an InitVar, it's
4342 # not an instance field.
4343 getattr(c, field_name)
4344
4345 if m.USING_STRINGS:
4346 # iv4 is interpreted as a normal field.
4347 self.assertIn('not_iv4', c.__dict__)
4348 self.assertEqual(c.not_iv4, 4)
4349 else:
4350 # iv4 is interpreted as an InitVar, so it
4351 # won't exist on the instance.
4352 self.assertNotIn('not_iv4', c.__dict__)
4353
4354 def test_text_annotations(self):
4355 from test.test_dataclasses import dataclass_textanno
4356
4357 self.assertEqual(
4358 get_type_hints(dataclass_textanno.Bar),
4359 {'foo': dataclass_textanno.Foo})
4360 self.assertEqual(
4361 get_type_hints(dataclass_textanno.Bar.__init__),
4362 {'foo': dataclass_textanno.Foo,
4363 'return': type(None)})
4364
4365
4366 ByMakeDataClass = make_dataclass('ByMakeDataClass', [('x', int)])
4367 ManualModuleMakeDataClass = make_dataclass('ManualModuleMakeDataClass',
4368 [('x', int)],
4369 module=__name__)
4370 WrongNameMakeDataclass = make_dataclass('Wrong', [('x', int)])
4371 WrongModuleMakeDataclass = make_dataclass('WrongModuleMakeDataclass',
4372 [('x', int)],
4373 module='custom')
4374
4375 class TestMakeDataclass(unittest.TestCase):
4376 def test_simple(self):
4377 C = make_dataclass('C',
4378 [('x', int),
4379 ('y', int, field(default=5))],
4380 namespace={'add_one': lambda self: self.x + 1})
4381 c = C(10)
4382 self.assertEqual((c.x, c.y), (10, 5))
4383 self.assertEqual(c.add_one(), 11)
4384
4385
4386 def test_no_mutate_namespace(self):
4387 # Make sure a provided namespace isn't mutated.
4388 ns = {}
4389 C = make_dataclass('C',
4390 [('x', int),
4391 ('y', int, field(default=5))],
4392 namespace=ns)
4393 self.assertEqual(ns, {})
4394
4395 def test_base(self):
4396 class Base1:
4397 pass
4398 class Base2:
4399 pass
4400 C = make_dataclass('C',
4401 [('x', int)],
4402 bases=(Base1, Base2))
4403 c = C(2)
4404 self.assertIsInstance(c, C)
4405 self.assertIsInstance(c, Base1)
4406 self.assertIsInstance(c, Base2)
4407
4408 def test_base_dataclass(self):
4409 @dataclass
4410 class Base1:
4411 x: int
4412 class Base2:
4413 pass
4414 C = make_dataclass('C',
4415 [('y', int)],
4416 bases=(Base1, Base2))
4417 with self.assertRaisesRegex(TypeError, 'required positional'):
4418 c = C(2)
4419 c = C(1, 2)
4420 self.assertIsInstance(c, C)
4421 self.assertIsInstance(c, Base1)
4422 self.assertIsInstance(c, Base2)
4423
4424 self.assertEqual((c.x, c.y), (1, 2))
4425
4426 def test_init_var(self):
4427 def post_init(self, y):
4428 self.x *= y
4429
4430 C = make_dataclass('C',
4431 [('x', int),
4432 ('y', InitVar[int]),
4433 ],
4434 namespace={'__post_init__': post_init},
4435 )
4436 c = C(2, 3)
4437 self.assertEqual(vars(c), {'x': 6})
4438 self.assertEqual(len(fields(c)), 1)
4439
4440 def test_class_var(self):
4441 C = make_dataclass('C',
4442 [('x', int),
4443 ('y', ClassVar[int], 10),
4444 ('z', ClassVar[int], field(default=20)),
4445 ])
4446 c = C(1)
4447 self.assertEqual(vars(c), {'x': 1})
4448 self.assertEqual(len(fields(c)), 1)
4449 self.assertEqual(C.y, 10)
4450 self.assertEqual(C.z, 20)
4451
4452 def test_other_params(self):
4453 C = make_dataclass('C',
4454 [('x', int),
4455 ('y', ClassVar[int], 10),
4456 ('z', ClassVar[int], field(default=20)),
4457 ],
4458 init=False)
4459 # Make sure we have a repr, but no init.
4460 self.assertNotIn('__init__', vars(C))
4461 self.assertIn('__repr__', vars(C))
4462
4463 # Make sure random other params don't work.
4464 with self.assertRaisesRegex(TypeError, 'unexpected keyword argument'):
4465 C = make_dataclass('C',
4466 [],
4467 xxinit=False)
4468
4469 def test_no_types(self):
4470 C = make_dataclass('Point', ['x', 'y', 'z'])
4471 c = C(1, 2, 3)
4472 self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})
4473 self.assertEqual(C.__annotations__, {'x': typing.Any,
4474 'y': typing.Any,
4475 'z': typing.Any})
4476
4477 C = make_dataclass('Point', ['x', ('y', int), 'z'])
4478 c = C(1, 2, 3)
4479 self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})
4480 self.assertEqual(C.__annotations__, {'x': typing.Any,
4481 'y': int,
4482 'z': typing.Any})
4483
4484 def test_no_types_get_annotations(self):
4485 C = make_dataclass('C', ['x', ('y', int), 'z'])
4486
4487 self.assertEqual(
4488 annotationlib.get_annotations(C, format=annotationlib.Format.VALUE),
4489 {'x': typing.Any, 'y': int, 'z': typing.Any},
4490 )
4491 self.assertEqual(
4492 annotationlib.get_annotations(
4493 C, format=annotationlib.Format.FORWARDREF),
4494 {'x': typing.Any, 'y': int, 'z': typing.Any},
4495 )
4496 self.assertEqual(
4497 annotationlib.get_annotations(
4498 C, format=annotationlib.Format.STRING),
4499 {'x': 'typing.Any', 'y': 'int', 'z': 'typing.Any'},
4500 )
4501
4502 def test_no_types_no_typing_import(self):
4503 with import_helper.CleanImport('typing'):
4504 self.assertNotIn('typing', sys.modules)
4505 C = make_dataclass('C', ['x', ('y', int)])
4506
4507 self.assertNotIn('typing', sys.modules)
4508 self.assertEqual(
4509 C.__annotate__(annotationlib.Format.FORWARDREF),
4510 {
4511 'x': annotationlib.ForwardRef('Any', module='typing'),
4512 'y': int,
4513 },
4514 )
4515 self.assertNotIn('typing', sys.modules)
4516
4517 for field in fields(C):
4518 if field.name == "x":
4519 self.assertEqual(field.type, annotationlib.ForwardRef('Any', module='typing'))
4520 else:
4521 self.assertEqual(field.name, "y")
4522 self.assertIs(field.type, int)
4523
4524 def test_module_attr(self):
4525 self.assertEqual(ByMakeDataClass.__module__, __name__)
4526 self.assertEqual(ByMakeDataClass(1).__module__, __name__)
4527 self.assertEqual(WrongModuleMakeDataclass.__module__, "custom")
4528 Nested = make_dataclass('Nested', [])
4529 self.assertEqual(Nested.__module__, __name__)
4530 self.assertEqual(Nested().__module__, __name__)
4531
4532 def test_pickle_support(self):
4533 for klass in [ByMakeDataClass, ManualModuleMakeDataClass]:
4534 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
4535 with self.subTest(proto=proto):
4536 self.assertEqual(
4537 pickle.loads(pickle.dumps(klass, proto)),
4538 klass,
4539 )
4540 self.assertEqual(
4541 pickle.loads(pickle.dumps(klass(1), proto)),
4542 klass(1),
4543 )
4544
4545 def test_cannot_be_pickled(self):
4546 for klass in [WrongNameMakeDataclass, WrongModuleMakeDataclass]:
4547 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
4548 with self.subTest(proto=proto):
4549 with self.assertRaises(pickle.PickleError):
4550 pickle.dumps(klass, proto)
4551 with self.assertRaises(pickle.PickleError):
4552 pickle.dumps(klass(1), proto)
4553
4554 def test_invalid_type_specification(self):
4555 for bad_field in [(),
4556 (1, 2, 3, 4),
4557 ]:
4558 with self.subTest(bad_field=bad_field):
4559 with self.assertRaisesRegex(TypeError, r'Invalid field: '):
4560 make_dataclass('C', ['a', bad_field])
4561
4562 # And test for things with no len().
4563 for bad_field in [float,
4564 lambda x:x,
4565 ]:
4566 with self.subTest(bad_field=bad_field):
4567 with self.assertRaisesRegex(TypeError, r'has no len\(\)'):
4568 make_dataclass('C', ['a', bad_field])
4569
4570 def test_duplicate_field_names(self):
4571 for field in ['a', 'ab']:
4572 with self.subTest(field=field):
4573 with self.assertRaisesRegex(TypeError, 'Field name duplicated'):
4574 make_dataclass('C', [field, 'a', field])
4575
4576 def test_keyword_field_names(self):
4577 for field in ['for', 'async', 'await', 'as']:
4578 with self.subTest(field=field):
4579 with self.assertRaisesRegex(TypeError, 'must not be keywords'):
4580 make_dataclass('C', ['a', field])
4581 with self.assertRaisesRegex(TypeError, 'must not be keywords'):
4582 make_dataclass('C', [field])
4583 with self.assertRaisesRegex(TypeError, 'must not be keywords'):
4584 make_dataclass('C', [field, 'a'])
4585
4586 def test_non_identifier_field_names(self):
4587 for field in ['()', 'x,y', '*', '2@3', '', 'little johnny tables']:
4588 with self.subTest(field=field):
4589 with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):
4590 make_dataclass('C', ['a', field])
4591 with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):
4592 make_dataclass('C', [field])
4593 with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):
4594 make_dataclass('C', [field, 'a'])
4595
4596 def test_underscore_field_names(self):
4597 # Unlike namedtuple, it's okay if dataclass field names have
4598 # an underscore.
4599 make_dataclass('C', ['_', '_a', 'a_a', 'a_'])
4600
4601 def test_funny_class_names_names(self):
4602 # No reason to prevent weird class names, since
4603 # types.new_class allows them.
4604 for classname in ['()', 'x,y', '*', '2@3', '']:
4605 with self.subTest(classname=classname):
4606 C = make_dataclass(classname, ['a', 'b'])
4607 self.assertEqual(C.__name__, classname)
4608
4609 def test_dataclass_decorator_default(self):
4610 C = make_dataclass('C', [('x', int)], decorator=dataclass)
4611 c = C(10)
4612 self.assertEqual(c.x, 10)
4613
4614 def test_dataclass_custom_decorator(self):
4615 def custom_dataclass(cls, *args, **kwargs):
4616 dc = dataclass(cls, *args, **kwargs)
4617 dc.__custom__ = True
4618 return dc
4619
4620 C = make_dataclass('C', [('x', int)], decorator=custom_dataclass)
4621 c = C(10)
4622 self.assertEqual(c.x, 10)
4623 self.assertEqual(c.__custom__, True)
4624
4625
4626 class TestReplace(unittest.TestCase):
4627 def test(self):
4628 @dataclass(frozen=True)
4629 class C:
4630 x: int
4631 y: int
4632
4633 c = C(1, 2)
4634 c1 = replace(c, x=3)
4635 self.assertEqual(c1.x, 3)
4636 self.assertEqual(c1.y, 2)
4637
4638 def test_frozen(self):
4639 @dataclass(frozen=True)
4640 class C:
4641 x: int
4642 y: int
4643 z: int = field(init=False, default=10)
4644 t: int = field(init=False, default=100)
4645
4646 c = C(1, 2)
4647 c1 = replace(c, x=3)
4648 self.assertEqual((c.x, c.y, c.z, c.t), (1, 2, 10, 100))
4649 self.assertEqual((c1.x, c1.y, c1.z, c1.t), (3, 2, 10, 100))
4650
4651
4652 with self.assertRaisesRegex(TypeError, 'init=False'):
4653 replace(c, x=3, z=20, t=50)
4654 with self.assertRaisesRegex(TypeError, 'init=False'):
4655 replace(c, z=20)
4656 replace(c, x=3, z=20, t=50)
4657
4658 # Make sure the result is still frozen.
4659 with self.assertRaisesRegex(FrozenInstanceError, "cannot assign to field 'x'"):
4660 c1.x = 3
4661
4662 # Make sure we can't replace an attribute that doesn't exist,
4663 # if we're also replacing one that does exist. Test this
4664 # here, because setting attributes on frozen instances is
4665 # handled slightly differently from non-frozen ones.
4666 with self.assertRaisesRegex(TypeError, r"__init__\(\) got an unexpected "
4667 "keyword argument 'a'"):
4668 c1 = replace(c, x=20, a=5)
4669
4670 def test_invalid_field_name(self):
4671 @dataclass(frozen=True)
4672 class C:
4673 x: int
4674 y: int
4675
4676 c = C(1, 2)
4677 with self.assertRaisesRegex(TypeError, r"__init__\(\) got an unexpected "
4678 "keyword argument 'z'"):
4679 c1 = replace(c, z=3)
4680
4681 def test_invalid_object(self):
4682 @dataclass(frozen=True)
4683 class C:
4684 x: int
4685 y: int
4686
4687 with self.assertRaisesRegex(TypeError, 'dataclass instance'):
4688 replace(C, x=3)
4689
4690 with self.assertRaisesRegex(TypeError, 'dataclass instance'):
4691 replace(0, x=3)
4692
4693 def test_no_init(self):
4694 @dataclass
4695 class C:
4696 x: int
4697 y: int = field(init=False, default=10)
4698
4699 c = C(1)
4700 c.y = 20
4701
4702 # Make sure y gets the default value.
4703 c1 = replace(c, x=5)
4704 self.assertEqual((c1.x, c1.y), (5, 10))
4705
4706 # Trying to replace y is an error.
4707 with self.assertRaisesRegex(TypeError, 'init=False'):
4708 replace(c, x=2, y=30)
4709
4710 with self.assertRaisesRegex(TypeError, 'init=False'):
4711 replace(c, y=30)
4712
4713 def test_classvar(self):
4714 @dataclass
4715 class C:
4716 x: int
4717 y: ClassVar[int] = 1000
4718
4719 c = C(1)
4720 d = C(2)
4721
4722 self.assertIs(c.y, d.y)
4723 self.assertEqual(c.y, 1000)
4724
4725 # Trying to replace y is an error: can't replace ClassVars.
4726 with self.assertRaisesRegex(TypeError, r"__init__\(\) got an "
4727 "unexpected keyword argument 'y'"):
4728 replace(c, y=30)
4729
4730 replace(c, x=5)
4731
4732 def test_initvar_is_specified(self):
4733 @dataclass
4734 class C:
4735 x: int
4736 y: InitVar[int]
4737
4738 def __post_init__(self, y):
4739 self.x *= y
4740
4741 c = C(1, 10)
4742 self.assertEqual(c.x, 10)
4743 with self.assertRaisesRegex(TypeError, r"InitVar 'y' must be "
4744 r"specified with replace\(\)"):
4745 replace(c, x=3)
4746 c = replace(c, x=3, y=5)
4747 self.assertEqual(c.x, 15)
4748
4749 def test_initvar_with_default_value(self):
4750 @dataclass
4751 class C:
4752 x: int
4753 y: InitVar[int] = None
4754 z: InitVar[int] = 42
4755
4756 def __post_init__(self, y, z):
4757 if y is not None:
4758 self.x += y
4759 if z is not None:
4760 self.x += z
4761
4762 c = C(x=1, y=10, z=1)
4763 self.assertEqual(replace(c), C(x=12))
4764 self.assertEqual(replace(c, y=4), C(x=12, y=4, z=42))
4765 self.assertEqual(replace(c, y=4, z=1), C(x=12, y=4, z=1))
4766
4767 def test_recursive_repr(self):
4768 @dataclass
4769 class C:
4770 f: "C"
4771
4772 c = C(None)
4773 c.f = c
4774 self.assertEqual(repr(c), "TestReplace.test_recursive_repr.<locals>.C(f=...)")
4775
4776 def test_recursive_repr_two_attrs(self):
4777 @dataclass
4778 class C:
4779 f: "C"
4780 g: "C"
4781
4782 c = C(None, None)
4783 c.f = c
4784 c.g = c
4785 self.assertEqual(repr(c), "TestReplace.test_recursive_repr_two_attrs"
4786 ".<locals>.C(f=..., g=...)")
4787
4788 def test_recursive_repr_indirection(self):
4789 @dataclass
4790 class C:
4791 f: "D"
4792
4793 @dataclass
4794 class D:
4795 f: "C"
4796
4797 c = C(None)
4798 d = D(None)
4799 c.f = d
4800 d.f = c
4801 self.assertEqual(repr(c), "TestReplace.test_recursive_repr_indirection"
4802 ".<locals>.C(f=TestReplace.test_recursive_repr_indirection"
4803 ".<locals>.D(f=...))")
4804
4805 def test_recursive_repr_indirection_two(self):
4806 @dataclass
4807 class C:
4808 f: "D"
4809
4810 @dataclass
4811 class D:
4812 f: "E"
4813
4814 @dataclass
4815 class E:
4816 f: "C"
4817
4818 c = C(None)
4819 d = D(None)
4820 e = E(None)
4821 c.f = d
4822 d.f = e
4823 e.f = c
4824 self.assertEqual(repr(c), "TestReplace.test_recursive_repr_indirection_two"
4825 ".<locals>.C(f=TestReplace.test_recursive_repr_indirection_two"
4826 ".<locals>.D(f=TestReplace.test_recursive_repr_indirection_two"
4827 ".<locals>.E(f=...)))")
4828
4829 def test_recursive_repr_misc_attrs(self):
4830 @dataclass
4831 class C:
4832 f: "C"
4833 g: int
4834
4835 c = C(None, 1)
4836 c.f = c
4837 self.assertEqual(repr(c), "TestReplace.test_recursive_repr_misc_attrs"
4838 ".<locals>.C(f=..., g=1)")
4839
4840 ## def test_initvar(self):
4841 ## @dataclass
4842 ## class C:
4843 ## x: int
4844 ## y: InitVar[int]
4845
4846 ## c = C(1, 10)
4847 ## d = C(2, 20)
4848
4849 ## # In our case, replacing an InitVar is a no-op
4850 ## self.assertEqual(c, replace(c, y=5))
4851
4852 ## replace(c, x=5)
4853
4854 class TestAbstract(unittest.TestCase):
4855 def test_abc_implementation(self):
4856 class Ordered(abc.ABC):
4857 @abc.abstractmethod
4858 def __lt__(self, other):
4859 pass
4860
4861 @abc.abstractmethod
4862 def __le__(self, other):
4863 pass
4864
4865 @dataclass(order=True)
4866 class Date(Ordered):
4867 year: int
4868 month: 'Month'
4869 day: 'int'
4870
4871 self.assertFalse(inspect.isabstract(Date))
4872 self.assertGreater(Date(2020,12,25), Date(2020,8,31))
4873
4874 def test_maintain_abc(self):
4875 class A(abc.ABC):
4876 @abc.abstractmethod
4877 def foo(self):
4878 pass
4879
4880 @dataclass
4881 class Date(A):
4882 year: int
4883 month: 'Month'
4884 day: 'int'
4885
4886 self.assertTrue(inspect.isabstract(Date))
4887 msg = "class Date without an implementation for abstract method 'foo'"
4888 self.assertRaisesRegex(TypeError, msg, Date)
4889
4890
4891 class TestMatchArgs(unittest.TestCase):
4892 def test_match_args(self):
4893 @dataclass
4894 class C:
4895 a: int
4896 self.assertEqual(C(42).__match_args__, ('a',))
4897
4898 def test_explicit_match_args(self):
4899 ma = ()
4900 @dataclass
4901 class C:
4902 a: int
4903 __match_args__ = ma
4904 self.assertIs(C(42).__match_args__, ma)
4905
4906 def test_bpo_43764(self):
4907 @dataclass(repr=False, eq=False, init=False)
4908 class X:
4909 a: int
4910 b: int
4911 c: int
4912 self.assertEqual(X.__match_args__, ("a", "b", "c"))
4913
4914 def test_match_args_argument(self):
4915 @dataclass(match_args=False)
4916 class X:
4917 a: int
4918 self.assertNotIn('__match_args__', X.__dict__)
4919
4920 @dataclass(match_args=False)
4921 class Y:
4922 a: int
4923 __match_args__ = ('b',)
4924 self.assertEqual(Y.__match_args__, ('b',))
4925
4926 @dataclass(match_args=False)
4927 class Z(Y):
4928 z: int
4929 self.assertEqual(Z.__match_args__, ('b',))
4930
4931 # Ensure parent dataclass __match_args__ is seen, if child class
4932 # specifies match_args=False.
4933 @dataclass
4934 class A:
4935 a: int
4936 z: int
4937 @dataclass(match_args=False)
4938 class B(A):
4939 b: int
4940 self.assertEqual(B.__match_args__, ('a', 'z'))
4941
4942 def test_make_dataclasses(self):
4943 C = make_dataclass('C', [('x', int), ('y', int)])
4944 self.assertEqual(C.__match_args__, ('x', 'y'))
4945
4946 C = make_dataclass('C', [('x', int), ('y', int)], match_args=True)
4947 self.assertEqual(C.__match_args__, ('x', 'y'))
4948
4949 C = make_dataclass('C', [('x', int), ('y', int)], match_args=False)
4950 self.assertNotIn('__match__args__', C.__dict__)
4951
4952 C = make_dataclass('C', [('x', int), ('y', int)], namespace={'__match_args__': ('z',)})
4953 self.assertEqual(C.__match_args__, ('z',))
4954
4955
4956 class TestKeywordArgs(unittest.TestCase):
4957 def test_no_classvar_kwarg(self):
4958 msg = 'field a is a ClassVar but specifies kw_only'
4959 with self.assertRaisesRegex(TypeError, msg):
4960 @dataclass
4961 class A:
4962 a: ClassVar[int] = field(kw_only=True)
4963
4964 with self.assertRaisesRegex(TypeError, msg):
4965 @dataclass
4966 class A:
4967 a: ClassVar[int] = field(kw_only=False)
4968
4969 with self.assertRaisesRegex(TypeError, msg):
4970 @dataclass(kw_only=True)
4971 class A:
4972 a: ClassVar[int] = field(kw_only=False)
4973
4974 def test_field_marked_as_kwonly(self):
4975 #######################
4976 # Using dataclass(kw_only=True)
4977 @dataclass(kw_only=True)
4978 class A:
4979 a: int
4980 self.assertTrue(fields(A)[0].kw_only)
4981
4982 @dataclass(kw_only=True)
4983 class A:
4984 a: int = field(kw_only=True)
4985 self.assertTrue(fields(A)[0].kw_only)
4986
4987 @dataclass(kw_only=True)
4988 class A:
4989 a: int = field(kw_only=False)
4990 self.assertFalse(fields(A)[0].kw_only)
4991
4992 #######################
4993 # Using dataclass(kw_only=False)
4994 @dataclass(kw_only=False)
4995 class A:
4996 a: int
4997 self.assertFalse(fields(A)[0].kw_only)
4998
4999 @dataclass(kw_only=False)
5000 class A:
5001 a: int = field(kw_only=True)
5002 self.assertTrue(fields(A)[0].kw_only)
5003
5004 @dataclass(kw_only=False)
5005 class A:
5006 a: int = field(kw_only=False)
5007 self.assertFalse(fields(A)[0].kw_only)
5008
5009 #######################
5010 # Not specifying dataclass(kw_only)
5011 @dataclass
5012 class A:
5013 a: int
5014 self.assertFalse(fields(A)[0].kw_only)
5015
5016 @dataclass
5017 class A:
5018 a: int = field(kw_only=True)
5019 self.assertTrue(fields(A)[0].kw_only)
5020
5021 @dataclass
5022 class A:
5023 a: int = field(kw_only=False)
5024 self.assertFalse(fields(A)[0].kw_only)
5025
5026 def test_match_args(self):
5027 # kw fields don't show up in __match_args__.
5028 @dataclass(kw_only=True)
5029 class C:
5030 a: int
5031 self.assertEqual(C(a=42).__match_args__, ())
5032
5033 @dataclass
5034 class C:
5035 a: int
5036 b: int = field(kw_only=True)
5037 self.assertEqual(C(42, b=10).__match_args__, ('a',))
5038
5039 def test_KW_ONLY(self):
5040 @dataclass
5041 class A:
5042 a: int
5043 _: KW_ONLY
5044 b: int
5045 c: int
5046 A(3, c=5, b=4)
5047 msg = "takes 2 positional arguments but 4 were given"
5048 with self.assertRaisesRegex(TypeError, msg):
5049 A(3, 4, 5)
5050
5051
5052 @dataclass(kw_only=True)
5053 class B:
5054 a: int
5055 _: KW_ONLY
5056 b: int
5057 c: int
5058 B(a=3, b=4, c=5)
5059 msg = "takes 1 positional argument but 4 were given"
5060 with self.assertRaisesRegex(TypeError, msg):
5061 B(3, 4, 5)
5062
5063 # Explicitly make a field that follows KW_ONLY be non-keyword-only.
5064 @dataclass
5065 class C:
5066 a: int
5067 _: KW_ONLY
5068 b: int
5069 c: int = field(kw_only=False)
5070 c = C(1, 2, b=3)
5071 self.assertEqual(c.a, 1)
5072 self.assertEqual(c.b, 3)
5073 self.assertEqual(c.c, 2)
5074 c = C(1, b=3, c=2)
5075 self.assertEqual(c.a, 1)
5076 self.assertEqual(c.b, 3)
5077 self.assertEqual(c.c, 2)
5078 c = C(1, b=3, c=2)
5079 self.assertEqual(c.a, 1)
5080 self.assertEqual(c.b, 3)
5081 self.assertEqual(c.c, 2)
5082 c = C(c=2, b=3, a=1)
5083 self.assertEqual(c.a, 1)
5084 self.assertEqual(c.b, 3)
5085 self.assertEqual(c.c, 2)
5086
5087 def test_KW_ONLY_as_string(self):
5088 @dataclass
5089 class A:
5090 a: int
5091 _: 'dataclasses.KW_ONLY'
5092 b: int
5093 c: int
5094 A(3, c=5, b=4)
5095 msg = "takes 2 positional arguments but 4 were given"
5096 with self.assertRaisesRegex(TypeError, msg):
5097 A(3, 4, 5)
5098
5099 def test_KW_ONLY_twice(self):
5100 msg = "'Y' is KW_ONLY, but KW_ONLY has already been specified"
5101
5102 with self.assertRaisesRegex(TypeError, msg):
5103 @dataclass
5104 class A:
5105 a: int
5106 X: KW_ONLY
5107 Y: KW_ONLY
5108 b: int
5109 c: int
5110
5111 with self.assertRaisesRegex(TypeError, msg):
5112 @dataclass
5113 class A:
5114 a: int
5115 X: KW_ONLY
5116 b: int
5117 Y: KW_ONLY
5118 c: int
5119
5120 with self.assertRaisesRegex(TypeError, msg):
5121 @dataclass
5122 class A:
5123 a: int
5124 X: KW_ONLY
5125 b: int
5126 c: int
5127 Y: KW_ONLY
5128
5129 # But this usage is okay, since it's not using KW_ONLY.
5130 @dataclass
5131 class NoDuplicateKwOnlyAnnotation:
5132 a: int
5133 _: KW_ONLY
5134 b: int
5135 c: int = field(kw_only=True)
5136
5137 # And if inheriting, it's okay.
5138 @dataclass
5139 class BaseUsesKwOnly:
5140 a: int
5141 _: KW_ONLY
5142 b: int
5143 c: int
5144 @dataclass
5145 class SubclassUsesKwOnly(BaseUsesKwOnly):
5146 _: KW_ONLY
5147 d: int
5148
5149 # Make sure the error is raised in a derived class.
5150 with self.assertRaisesRegex(TypeError, msg):
5151 @dataclass
5152 class A:
5153 a: int
5154 _: KW_ONLY
5155 b: int
5156 c: int
5157 @dataclass
5158 class B(A):
5159 X: KW_ONLY
5160 d: int
5161 Y: KW_ONLY
5162
5163
5164 def test_post_init(self):
5165 @dataclass
5166 class A:
5167 a: int
5168 _: KW_ONLY
5169 b: InitVar[int]
5170 c: int
5171 d: InitVar[int]
5172 def __post_init__(self, b, d):
5173 raise CustomError(f'{b=} {d=}')
5174 with self.assertRaisesRegex(CustomError, 'b=3 d=4'):
5175 A(1, c=2, b=3, d=4)
5176
5177 @dataclass
5178 class B:
5179 a: int
5180 _: KW_ONLY
5181 b: InitVar[int]
5182 c: int
5183 d: InitVar[int]
5184 def __post_init__(self, b, d):
5185 self.a = b
5186 self.c = d
5187 b = B(1, c=2, b=3, d=4)
5188 self.assertEqual(asdict(b), {'a': 3, 'c': 4})
5189
5190 def test_defaults(self):
5191 # For kwargs, make sure we can have defaults after non-defaults.
5192 @dataclass
5193 class A:
5194 a: int = 0
5195 _: KW_ONLY
5196 b: int
5197 c: int = 1
5198 d: int
5199
5200 a = A(d=4, b=3)
5201 self.assertEqual(a.a, 0)
5202 self.assertEqual(a.b, 3)
5203 self.assertEqual(a.c, 1)
5204 self.assertEqual(a.d, 4)
5205
5206 # Make sure we still check for non-kwarg non-defaults not following
5207 # defaults.
5208 err_regex = "non-default argument 'z' follows default argument 'a'"
5209 with self.assertRaisesRegex(TypeError, err_regex):
5210 @dataclass
5211 class A:
5212 a: int = 0
5213 z: int
5214 _: KW_ONLY
5215 b: int
5216 c: int = 1
5217 d: int
5218
5219 def test_make_dataclass(self):
5220 A = make_dataclass("A", ['a'], kw_only=True)
5221 self.assertTrue(fields(A)[0].kw_only)
5222
5223 B = make_dataclass("B",
5224 ['a', ('b', int, field(kw_only=False))],
5225 kw_only=True)
5226 self.assertTrue(fields(B)[0].kw_only)
5227 self.assertFalse(fields(B)[1].kw_only)
5228
5229 def test_deferred_annotations(self):
5230 @dataclass
5231 class A:
5232 x: undefined
5233 y: ClassVar[undefined]
5234
5235 fs = fields(A)
5236 self.assertEqual(len(fs), 1)
5237 self.assertEqual(fs[0].name, 'x')
5238
5239
5240 class TestZeroArgumentSuperWithSlots(unittest.TestCase):
5241 def test_zero_argument_super(self):
5242 @dataclass(slots=True)
5243 class A:
5244 def foo(self):
5245 super()
5246
5247 A().foo()
5248
5249 def test_dunder_class_with_old_property(self):
5250 @dataclass(slots=True)
5251 class A:
5252 def _get_foo(slf):
5253 self.assertIs(__class__, type(slf))
5254 self.assertIs(__class__, slf.__class__)
5255 return __class__
5256
5257 def _set_foo(slf, value):
5258 self.assertIs(__class__, type(slf))
5259 self.assertIs(__class__, slf.__class__)
5260
5261 def _del_foo(slf):
5262 self.assertIs(__class__, type(slf))
5263 self.assertIs(__class__, slf.__class__)
5264
5265 foo = property(_get_foo, _set_foo, _del_foo)
5266
5267 a = A()
5268 self.assertIs(a.foo, A)
5269 a.foo = 4
5270 del a.foo
5271
5272 def test_dunder_class_with_new_property(self):
5273 @dataclass(slots=True)
5274 class A:
5275 @property
5276 def foo(slf):
5277 return slf.__class__
5278
5279 @foo.setter
5280 def foo(slf, value):
5281 self.assertIs(__class__, type(slf))
5282
5283 @foo.deleter
5284 def foo(slf):
5285 self.assertIs(__class__, type(slf))
5286
5287 a = A()
5288 self.assertIs(a.foo, A)
5289 a.foo = 4
5290 del a.foo
5291
5292 # Test the parts of a property individually.
5293 def test_slots_dunder_class_property_getter(self):
5294 @dataclass(slots=True)
5295 class A:
5296 @property
5297 def foo(slf):
5298 return __class__
5299
5300 a = A()
5301 self.assertIs(a.foo, A)
5302
5303 def test_slots_dunder_class_property_setter(self):
5304 @dataclass(slots=True)
5305 class A:
5306 foo = property()
5307 @foo.setter
5308 def foo(slf, val):
5309 self.assertIs(__class__, type(slf))
5310
5311 a = A()
5312 a.foo = 4
5313
5314 def test_slots_dunder_class_property_deleter(self):
5315 @dataclass(slots=True)
5316 class A:
5317 foo = property()
5318 @foo.deleter
5319 def foo(slf):
5320 self.assertIs(__class__, type(slf))
5321
5322 a = A()
5323 del a.foo
5324
5325 def test_wrapped(self):
5326 def mydecorator(f):
5327 @wraps(f)
5328 def wrapper(*args, **kwargs):
5329 return f(*args, **kwargs)
5330 return wrapper
5331
5332 @dataclass(slots=True)
5333 class A:
5334 @mydecorator
5335 def foo(self):
5336 super()
5337
5338 A().foo()
5339
5340 def test_remembered_class(self):
5341 # Apply the dataclass decorator manually (not when the class
5342 # is created), so that we can keep a reference to the
5343 # undecorated class.
5344 class A:
5345 def cls(self):
5346 return __class__
5347
5348 self.assertIs(A().cls(), A)
5349
5350 B = dataclass(slots=True)(A)
5351 self.assertIs(B().cls(), B)
5352
5353 # This is undesirable behavior, but is a function of how
5354 # modifying __class__ in the closure works. I'm not sure this
5355 # should be tested or not: I don't really want to guarantee
5356 # this behavior, but I don't want to lose the point that this
5357 # is how it works.
5358
5359 # The underlying class is "broken" by changing its __class__
5360 # in A.foo() to B. This normally isn't a problem, because no
5361 # one will be keeping a reference to the underlying class A.
5362 self.assertIs(A().cls(), B)
5363
5364 def test_empty_class_cell(self):
5365 # gh-148947: Make sure that we explicitly handle the empty class cell.
5366 def maker():
5367 if False:
5368 __class__ = 42
5369
5370 def method(self):
5371 return __class__
5372 return method
5373
5374 from dataclasses import dataclass
5375
5376 @dataclass(slots=True)
5377 class X:
5378 a: int
5379
5380 meth = maker()
5381
5382 with self.assertRaisesRegex(NameError, '__class__'):
5383 X(1).meth()
5384
5385 def test_class_cell_from_other_class(self):
5386 # This test fails without the "is oldcls" check in
5387 # _update_func_cell_for__class__.
5388 class Base:
5389 def meth(self):
5390 return "Base"
5391
5392 class Child(Base):
5393 def meth(self):
5394 return super().meth() + " Child"
5395
5396 @dataclass(slots=True)
5397 class DC(Child):
5398 a: int
5399
5400 meth = Child.meth
5401
5402 closure = DC.meth.__closure__
5403 self.assertEqual(len(closure), 1)
5404 self.assertIs(closure[0].cell_contents, Child)
5405
5406 self.assertEqual(DC(1).meth(), "Base Child")
5407
5408
5409
5410 if __name__ == '__main__':
5411 unittest.main()