Debian Codegraph @

lib-python/3/test/test_dataclasses/__init__.py

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