Debian Codegraph @

Lib/test/test_dataclasses/__init__.py

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