Debian Codegraph @

tests/brain/test_dataclasses.py

raw
1 # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
2 # For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
3 # Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
4
5 import pytest
6
7 import astroid
8 from astroid import bases, nodes
9 from astroid.exceptions import InferenceError
10 from astroid.util import Uninferable
11
12 parametrize_module = pytest.mark.parametrize(
13 ("module",), (["dataclasses"], ["pydantic.dataclasses"], ["marshmallow_dataclass"])
14 )
15
16
17 @parametrize_module
18 def test_inference_attribute_no_default(module: str):
19 """Test inference of dataclass attribute with no default.
20
21 Note that the argument to the constructor is ignored by the inference.
22 """
23 klass, instance = astroid.extract_node(f"""
24 from {module} import dataclass
25
26 @dataclass
27 class A:
28 name: str
29
30 A.name #@
31 A('hi').name #@
32 """)
33 with pytest.raises(InferenceError):
34 klass.inferred()
35
36 inferred = instance.inferred()
37 assert len(inferred) == 1
38 assert isinstance(inferred[0], bases.Instance)
39 assert inferred[0].name == "str"
40
41
42 @parametrize_module
43 def test_inference_non_field_default(module: str):
44 """Test inference of dataclass attribute with a non-field default."""
45 klass, instance = astroid.extract_node(f"""
46 from {module} import dataclass
47
48 @dataclass
49 class A:
50 name: str = 'hi'
51
52 A.name #@
53 A().name #@
54 """)
55 inferred = klass.inferred()
56 assert len(inferred) == 1
57 assert isinstance(inferred[0], nodes.Const)
58 assert inferred[0].value == "hi"
59
60 inferred = instance.inferred()
61 assert len(inferred) == 2
62 assert isinstance(inferred[0], nodes.Const)
63 assert inferred[0].value == "hi"
64
65 assert isinstance(inferred[1], bases.Instance)
66 assert inferred[1].name == "str"
67
68
69 @parametrize_module
70 def test_inference_field_default(module: str):
71 """Test inference of dataclass attribute with a field call default
72 (default keyword argument given).
73 """
74 klass, instance = astroid.extract_node(f"""
75 from {module} import dataclass
76 from dataclasses import field
77
78 @dataclass
79 class A:
80 name: str = field(default='hi')
81
82 A.name #@
83 A().name #@
84 """)
85 inferred = klass.inferred()
86 assert len(inferred) == 1
87 assert isinstance(inferred[0], nodes.Const)
88 assert inferred[0].value == "hi"
89
90 inferred = instance.inferred()
91 assert len(inferred) == 2
92 assert isinstance(inferred[0], nodes.Const)
93 assert inferred[0].value == "hi"
94
95 assert isinstance(inferred[1], bases.Instance)
96 assert inferred[1].name == "str"
97
98
99 @parametrize_module
100 def test_inference_field_default_factory(module: str):
101 """Test inference of dataclass attribute with a field call default
102 (default_factory keyword argument given).
103 """
104 klass, instance = astroid.extract_node(f"""
105 from {module} import dataclass
106 from dataclasses import field
107
108 @dataclass
109 class A:
110 name: list = field(default_factory=list)
111
112 A.name #@
113 A().name #@
114 """)
115 inferred = klass.inferred()
116 assert len(inferred) == 1
117 assert isinstance(inferred[0], nodes.List)
118 assert inferred[0].elts == []
119
120 inferred = instance.inferred()
121 assert len(inferred) == 2
122 assert isinstance(inferred[0], nodes.List)
123 assert inferred[0].elts == []
124
125 assert isinstance(inferred[1], bases.Instance)
126 assert inferred[1].name == "list"
127
128
129 @parametrize_module
130 def test_inference_method(module: str):
131 """Test inference of dataclass attribute within a method,
132 with a default_factory field.
133
134 Based on https://github.com/pylint-dev/pylint/issues/2600
135 """
136 node = astroid.extract_node(f"""
137 from typing import Dict
138 from {module} import dataclass
139 from dataclasses import field
140
141 @dataclass
142 class TestClass:
143 foo: str
144 bar: str
145 baz_dict: Dict[str, str] = field(default_factory=dict)
146
147 def some_func(self) -> None:
148 f = self.baz_dict.items #@
149 for key, value in f():
150 print(key)
151 print(value)
152 """)
153 inferred = next(node.value.infer())
154 assert isinstance(inferred, bases.BoundMethod)
155
156
157 @parametrize_module
158 def test_inference_no_annotation(module: str):
159 """Test that class variables without type annotations are not
160 turned into instance attributes.
161 """
162 class_def, klass, instance = astroid.extract_node(f"""
163 from {module} import dataclass
164
165 @dataclass
166 class A:
167 name = 'hi'
168
169 A #@
170 A.name #@
171 A().name #@
172 """)
173 inferred = next(class_def.infer())
174 assert isinstance(inferred, nodes.ClassDef)
175 assert inferred.instance_attrs == {}
176 assert inferred.is_dataclass
177
178 # Both the class and instance can still access the attribute
179 for node in (klass, instance):
180 assert isinstance(node, nodes.NodeNG)
181 inferred = node.inferred()
182 assert len(inferred) == 1
183 assert isinstance(inferred[0], nodes.Const)
184 assert inferred[0].value == "hi"
185
186
187 @parametrize_module
188 def test_inference_class_var(module: str):
189 """Test that class variables with a ClassVar type annotations are not
190 turned into instance attributes.
191 """
192 class_def, klass, instance = astroid.extract_node(f"""
193 from {module} import dataclass
194 from typing import ClassVar
195
196 @dataclass
197 class A:
198 name: ClassVar[str] = 'hi'
199
200 A #@
201 A.name #@
202 A().name #@
203 """)
204 inferred = next(class_def.infer())
205 assert isinstance(inferred, nodes.ClassDef)
206 assert inferred.instance_attrs == {}
207 assert inferred.is_dataclass
208
209 # Both the class and instance can still access the attribute
210 for node in (klass, instance):
211 assert isinstance(node, nodes.NodeNG)
212 inferred = node.inferred()
213 assert len(inferred) == 1
214 assert isinstance(inferred[0], nodes.Const)
215 assert inferred[0].value == "hi"
216
217
218 @parametrize_module
219 def test_inference_init_var(module: str):
220 """Test that class variables with InitVar type annotations are not
221 turned into instance attributes.
222 """
223 class_def, klass, instance = astroid.extract_node(f"""
224 from {module} import dataclass
225 from dataclasses import InitVar
226
227 @dataclass
228 class A:
229 name: InitVar[str] = 'hi'
230
231 A #@
232 A.name #@
233 A().name #@
234 """)
235 inferred = next(class_def.infer())
236 assert isinstance(inferred, nodes.ClassDef)
237 assert inferred.instance_attrs == {}
238 assert inferred.is_dataclass
239
240 # Both the class and instance can still access the attribute
241 for node in (klass, instance):
242 assert isinstance(node, nodes.NodeNG)
243 inferred = node.inferred()
244 assert len(inferred) == 1
245 assert isinstance(inferred[0], nodes.Const)
246 assert inferred[0].value == "hi"
247
248
249 @parametrize_module
250 def test_inference_generic_collection_attribute(module: str):
251 """Test that an attribute with a generic collection type from the
252 typing module is inferred correctly.
253 """
254 attr_nodes = astroid.extract_node(f"""
255 from {module} import dataclass
256 from dataclasses import field
257 import typing
258
259 @dataclass
260 class A:
261 dict_prop: typing.Dict[str, str]
262 frozenset_prop: typing.FrozenSet[str]
263 list_prop: typing.List[str]
264 set_prop: typing.Set[str]
265 tuple_prop: typing.Tuple[int, str]
266
267 a = A({{}}, frozenset(), [], set(), (1, 'hi'))
268 a.dict_prop #@
269 a.frozenset_prop #@
270 a.list_prop #@
271 a.set_prop #@
272 a.tuple_prop #@
273 """)
274 names = (
275 "Dict",
276 "FrozenSet",
277 "List",
278 "Set",
279 "Tuple",
280 )
281 for node, name in zip(attr_nodes, names):
282 inferred = next(node.infer())
283 assert isinstance(inferred, bases.Instance)
284 assert inferred.name == name
285
286
287 @pytest.mark.parametrize(
288 ("module", "typing_module"),
289 [
290 ("dataclasses", "typing"),
291 ("pydantic.dataclasses", "typing"),
292 ("pydantic.dataclasses", "collections.abc"),
293 ("marshmallow_dataclass", "typing"),
294 ("marshmallow_dataclass", "collections.abc"),
295 ],
296 )
297 def test_inference_callable_attribute(module: str, typing_module: str):
298 """Test that an attribute with a Callable annotation is inferred as Uninferable.
299
300 See issue #1129 and pylint-dev/pylint#4895
301 """
302 instance = astroid.extract_node(f"""
303 from {module} import dataclass
304 from {typing_module} import Any, Callable
305
306 @dataclass
307 class A:
308 enabled: Callable[[Any], bool]
309
310 A(lambda x: x == 42).enabled #@
311 """)
312 inferred = next(instance.infer())
313 assert inferred is Uninferable
314
315
316 @parametrize_module
317 def test_inference_inherited(module: str):
318 """Test that an attribute is inherited from a superclass dataclass."""
319 klass1, instance1, klass2, instance2 = astroid.extract_node(f"""
320 from {module} import dataclass
321
322 @dataclass
323 class A:
324 value: int
325 name: str = "hi"
326
327 @dataclass
328 class B(A):
329 new_attr: bool = True
330
331 B.value #@
332 B(1).value #@
333 B.name #@
334 B(1).name #@
335 """)
336 with pytest.raises(InferenceError): # B.value is not defined
337 klass1.inferred()
338
339 inferred = instance1.inferred()
340 assert isinstance(inferred[0], bases.Instance)
341 assert inferred[0].name == "int"
342
343 inferred = klass2.inferred()
344 assert len(inferred) == 1
345 assert isinstance(inferred[0], nodes.Const)
346 assert inferred[0].value == "hi"
347
348 inferred = instance2.inferred()
349 assert len(inferred) == 2
350 assert isinstance(inferred[0], nodes.Const)
351 assert inferred[0].value == "hi"
352 assert isinstance(inferred[1], bases.Instance)
353 assert inferred[1].name == "str"
354
355
356 def test_dataclass_order_of_inherited_attributes():
357 """Test that an attribute in a child does not get put at the end of the init."""
358 child, normal, keyword_only = astroid.extract_node("""
359 from dataclass import dataclass
360
361
362 @dataclass
363 class Parent:
364 a: str
365 b: str
366
367
368 @dataclass
369 class Child(Parent):
370 c: str
371 a: str
372
373
374 @dataclass(kw_only=True)
375 class KeywordOnlyParent:
376 a: int
377 b: str
378
379
380 @dataclass
381 class NormalChild(KeywordOnlyParent):
382 c: str
383 a: str
384
385
386 @dataclass(kw_only=True)
387 class KeywordOnlyChild(KeywordOnlyParent):
388 c: str
389 a: str
390
391
392 Child.__init__ #@
393 NormalChild.__init__ #@
394 KeywordOnlyChild.__init__ #@
395 """)
396 child_init: bases.UnboundMethod = next(child.infer())
397 assert [a.name for a in child_init.args.args] == ["self", "a", "b", "c"]
398
399 normal_init: bases.UnboundMethod = next(normal.infer())
400 assert [a.name for a in normal_init.args.args] == ["self", "a", "c"]
401 assert [a.name for a in normal_init.args.kwonlyargs] == ["b"]
402
403 keyword_only_init: bases.UnboundMethod = next(keyword_only.infer())
404 assert [a.name for a in keyword_only_init.args.args] == ["self"]
405 assert [a.name for a in keyword_only_init.args.kwonlyargs] == ["a", "b", "c"]
406
407
408 def test_pydantic_field() -> None:
409 """Test that pydantic.Field attributes are currently Uninferable.
410
411 (Eventually, we can extend the brain to support pydantic.Field)
412 """
413 klass, instance = astroid.extract_node("""
414 from pydantic import Field
415 from pydantic.dataclasses import dataclass
416
417 @dataclass
418 class A:
419 name: str = Field("hi")
420
421 A.name #@
422 A().name #@
423 """)
424
425 inferred = klass.inferred()
426 assert len(inferred) == 1
427 assert inferred[0] is Uninferable
428
429 inferred = instance.inferred()
430 assert len(inferred) == 2
431 assert inferred[0] is Uninferable
432 assert isinstance(inferred[1], bases.Instance)
433 assert inferred[1].name == "str"
434
435
436 @parametrize_module
437 def test_init_empty(module: str):
438 """Test init for a dataclass with no attributes."""
439 node = astroid.extract_node(f"""
440 from {module} import dataclass
441
442 @dataclass
443 class A:
444 pass
445
446 A.__init__ #@
447 """)
448 init = next(node.infer())
449 assert [a.name for a in init.args.args] == ["self"]
450
451
452 @parametrize_module
453 def test_init_no_defaults(module: str):
454 """Test init for a dataclass with attributes and no defaults."""
455 node = astroid.extract_node(f"""
456 from {module} import dataclass
457 from typing import List
458
459 @dataclass
460 class A:
461 x: int
462 y: str
463 z: List[bool]
464
465 A.__init__ #@
466 """)
467 init = next(node.infer())
468 assert [a.name for a in init.args.args] == ["self", "x", "y", "z"]
469 assert [a.as_string() if a else None for a in init.args.annotations] == [
470 None,
471 "int",
472 "str",
473 "List[bool]",
474 ]
475
476
477 @parametrize_module
478 def test_init_defaults(module: str):
479 """Test init for a dataclass with attributes and some defaults."""
480 node = astroid.extract_node(f"""
481 from {module} import dataclass
482 from dataclasses import field
483 from typing import List
484
485 @dataclass
486 class A:
487 w: int
488 x: int = 10
489 y: str = field(default="hi")
490 z: List[bool] = field(default_factory=list)
491
492 A.__init__ #@
493 """)
494 init = next(node.infer())
495 assert [a.name for a in init.args.args] == ["self", "w", "x", "y", "z"]
496 assert [a.as_string() if a else None for a in init.args.annotations] == [
497 None,
498 "int",
499 "int",
500 "str",
501 "List[bool]",
502 ]
503 assert [a.as_string() if a else None for a in init.args.defaults] == [
504 "10",
505 "'hi'",
506 "_HAS_DEFAULT_FACTORY",
507 ]
508
509
510 @parametrize_module
511 def test_default_factory_sentinel_only_added_when_needed(module: str):
512 """The _HAS_DEFAULT_FACTORY sentinel should not leak into module locals.
513
514 It is only needed as a default for fields using ``default_factory``.
515 """
516 without_factory = astroid.parse(f"""
517 from {module} import dataclass
518
519 @dataclass
520 class A:
521 x: int = 10
522 """)
523 assert "_HAS_DEFAULT_FACTORY" not in without_factory.locals
524
525 with_factory = astroid.parse(f"""
526 from {module} import dataclass
527 from dataclasses import field
528 from typing import List
529
530 @dataclass
531 class A:
532 x: List[int] = field(default_factory=list)
533 """)
534 assert "_HAS_DEFAULT_FACTORY" in with_factory.locals
535
536
537 @parametrize_module
538 def test_init_initvar(module: str):
539 """Test init for a dataclass with attributes and an InitVar."""
540 node = astroid.extract_node(f"""
541 from {module} import dataclass
542 from dataclasses import InitVar
543 from typing import List
544
545 @dataclass
546 class A:
547 x: int
548 y: str
549 init_var: InitVar[int]
550 z: List[bool]
551
552 A.__init__ #@
553 """)
554 init = next(node.infer())
555 assert [a.name for a in init.args.args] == ["self", "x", "y", "init_var", "z"]
556 assert [a.as_string() if a else None for a in init.args.annotations] == [
557 None,
558 "int",
559 "str",
560 "int",
561 "List[bool]",
562 ]
563
564
565 @parametrize_module
566 def test_init_decorator_init_false(module: str):
567 """Test that no init is generated when init=False is passed to
568 dataclass decorator.
569 """
570 node = astroid.extract_node(f"""
571 from {module} import dataclass
572 from typing import List
573
574 @dataclass(init=False)
575 class A:
576 x: int
577 y: str
578 z: List[bool]
579
580 A.__init__ #@
581 """)
582 init = next(node.infer())
583 assert init._proxied.parent.name == "object"
584
585
586 @parametrize_module
587 def test_init_field_init_false(module: str):
588 """Test init for a dataclass with attributes with a field value where init=False
589 (these attributes should not be included in the initializer).
590 """
591 node = astroid.extract_node(f"""
592 from {module} import dataclass
593 from dataclasses import field
594 from typing import List
595
596 @dataclass
597 class A:
598 x: int
599 y: str
600 z: List[bool] = field(init=False)
601
602 A.__init__ #@
603 """)
604 init = next(node.infer())
605 assert [a.name for a in init.args.args] == ["self", "x", "y"]
606 assert [a.as_string() if a else None for a in init.args.annotations] == [
607 None,
608 "int",
609 "str",
610 ]
611
612
613 @parametrize_module
614 def test_init_override(module: str):
615 """Test init for a dataclass overrides a superclass initializer.
616
617 Based on https://github.com/pylint-dev/pylint/issues/3201
618 """
619 node = astroid.extract_node(f"""
620 from {module} import dataclass
621 from typing import List
622
623 class A:
624 arg0: str = None
625
626 def __init__(self, arg0):
627 raise NotImplementedError
628
629 @dataclass
630 class B(A):
631 arg1: int = None
632 arg2: str = None
633
634 B.__init__ #@
635 """)
636 init = next(node.infer())
637 assert [a.name for a in init.args.args] == ["self", "arg1", "arg2"]
638 assert [a.as_string() if a else None for a in init.args.annotations] == [
639 None,
640 "int",
641 "str",
642 ]
643
644
645 @parametrize_module
646 def test_init_attributes_from_superclasses(module: str):
647 """Test init for a dataclass that inherits and overrides attributes from
648 superclasses.
649
650 Based on https://github.com/pylint-dev/pylint/issues/3201
651 """
652 node = astroid.extract_node(f"""
653 from {module} import dataclass
654 from typing import List
655
656 @dataclass
657 class A:
658 arg0: float
659 arg2: str
660
661 @dataclass
662 class B(A):
663 arg1: int
664 arg2: list # Overrides arg2 from A
665
666 B.__init__ #@
667 """)
668 init = next(node.infer())
669 assert [a.name for a in init.args.args] == ["self", "arg0", "arg2", "arg1"]
670 assert [a.as_string() if a else None for a in init.args.annotations] == [
671 None,
672 "float",
673 "list", # not str
674 "int",
675 ]
676
677
678 @parametrize_module
679 def test_invalid_init(module: str):
680 """Test that astroid doesn't generate an initializer when attribute order is
681 invalid.
682 """
683 node = astroid.extract_node(f"""
684 from {module} import dataclass
685
686 @dataclass
687 class A:
688 arg1: float = 0.0
689 arg2: str
690
691 A.__init__ #@
692 """)
693 init = next(node.infer())
694 assert init._proxied.parent.name == "object"
695
696
697 @parametrize_module
698 def test_annotated_enclosed_field_call(module: str):
699 """Test inference of dataclass attribute with a field call in another function
700 call.
701 """
702 node = astroid.extract_node(f"""
703 from {module} import dataclass, field
704 from typing import cast
705
706 @dataclass
707 class A:
708 attribute: int = cast(int, field(default_factory=dict))
709 """)
710 inferred = node.inferred()
711 assert len(inferred) == 1 and isinstance(inferred[0], nodes.ClassDef)
712 assert "attribute" in inferred[0].instance_attrs
713 assert inferred[0].is_dataclass
714
715
716 @parametrize_module
717 def test_invalid_field_call(module: str) -> None:
718 """Test inference of invalid field call doesn't crash."""
719 code = astroid.extract_node(f"""
720 from {module} import dataclass, field
721
722 @dataclass
723 class A:
724 val: field()
725 """)
726 inferred = code.inferred()
727 assert len(inferred) == 1
728 assert isinstance(inferred[0], nodes.ClassDef)
729 assert inferred[0].is_dataclass
730
731
732 def test_non_dataclass_is_not_dataclass() -> None:
733 """Test that something that isn't a dataclass has the correct attribute."""
734 module = astroid.parse("""
735 class A:
736 val: field()
737
738 def dataclass():
739 return
740
741 @dataclass
742 class B:
743 val: field()
744 """)
745 class_a = module.body[0].inferred()
746 assert len(class_a) == 1
747 assert isinstance(class_a[0], nodes.ClassDef)
748 assert not class_a[0].is_dataclass
749
750 class_b = module.body[2].inferred()
751 assert len(class_b) == 1
752 assert isinstance(class_b[0], nodes.ClassDef)
753 assert not class_b[0].is_dataclass
754
755
756 def test_kw_only_sentinel() -> None:
757 """Test that the KW_ONLY sentinel doesn't get added to the fields."""
758 node_one, node_two, node_three = astroid.extract_node("""
759 import dataclasses
760 from dataclasses import dataclass, KW_ONLY
761 from dataclasses import KW_ONLY as keyword_only
762
763 @dataclass
764 class A:
765 _: KW_ONLY
766 y: str
767
768 A.__init__ #@
769
770 @dataclass
771 class B:
772 _: keyword_only
773 y: str
774
775 B.__init__ #@
776
777 @dataclass
778 class C:
779 _: dataclasses.KW_ONLY
780 y: str
781
782 C.__init__ #@
783 """)
784 expected = ["self", "y"]
785 for node in (node_one, node_two, node_three):
786 init = next(node.infer())
787 assert [a.name for a in init.args.args] == expected
788
789
790 def test_kw_only_sentinel_other_dataclasses_attr() -> None:
791 """Annotating with another ``dataclasses`` attribute (e.g. ``MISSING``)
792 that also infers to ``builtins.sentinel`` on Python 3.15+ must not be
793 treated as ``KW_ONLY``."""
794 node = astroid.extract_node("""
795 import dataclasses
796 from dataclasses import dataclass
797
798 @dataclass
799 class C:
800 _: dataclasses.MISSING
801 y: str
802
803 C.__init__ #@
804 """)
805 init = next(node.infer())
806 assert [a.name for a in init.args.args] == ["self", "_", "y"]
807
808
809 def test_kw_only_decorator() -> None:
810 """Test that we update the signature correctly based on the keyword."""
811 foodef, bardef, cee, dee = astroid.extract_node("""
812 from dataclasses import dataclass
813
814 @dataclass(kw_only=True)
815 class Foo:
816 a: int
817 e: str
818
819
820 @dataclass(kw_only=False)
821 class Bar(Foo):
822 c: int
823
824
825 @dataclass(kw_only=False)
826 class Cee(Bar):
827 d: int
828
829
830 @dataclass(kw_only=True)
831 class Dee(Cee):
832 ee: int
833
834
835 Foo.__init__ #@
836 Bar.__init__ #@
837 Cee.__init__ #@
838 Dee.__init__ #@
839 """)
840
841 foo_init: bases.UnboundMethod = next(foodef.infer())
842 assert [a.name for a in foo_init.args.args] == ["self"]
843 assert [a.name for a in foo_init.args.kwonlyargs] == ["a", "e"]
844
845 bar_init: bases.UnboundMethod = next(bardef.infer())
846 assert [a.name for a in bar_init.args.args] == ["self", "c"]
847 assert [a.name for a in bar_init.args.kwonlyargs] == ["a", "e"]
848
849 cee_init: bases.UnboundMethod = next(cee.infer())
850 assert [a.name for a in cee_init.args.args] == ["self", "c", "d"]
851 assert [a.name for a in cee_init.args.kwonlyargs] == ["a", "e"]
852
853 dee_init: bases.UnboundMethod = next(dee.infer())
854 assert [a.name for a in dee_init.args.args] == ["self", "c", "d"]
855 assert [a.name for a in dee_init.args.kwonlyargs] == ["a", "e", "ee"]
856
857
858 def test_kw_only_in_field_call() -> None:
859 """Test that keyword only fields get correctly put at the end of the __init__."""
860
861 first, second, third = astroid.extract_node("""
862 from dataclasses import dataclass, field
863
864 @dataclass
865 class Parent:
866 p1: int = field(kw_only=True, default=0)
867
868 @dataclass
869 class Child(Parent):
870 c1: str
871
872 @dataclass(kw_only=True)
873 class GrandChild(Child):
874 p2: int = field(kw_only=False, default=1)
875 p3: int = field(kw_only=True, default=2)
876
877 Parent.__init__ #@
878 Child.__init__ #@
879 GrandChild.__init__ #@
880 """)
881
882 first_init: bases.UnboundMethod = next(first.infer())
883 assert [a.name for a in first_init.args.args] == ["self"]
884 assert [a.name for a in first_init.args.kwonlyargs] == ["p1"]
885 assert [d.value for d in first_init.args.kw_defaults] == [0]
886
887 second_init: bases.UnboundMethod = next(second.infer())
888 assert [a.name for a in second_init.args.args] == ["self", "c1"]
889 assert [a.name for a in second_init.args.kwonlyargs] == ["p1"]
890 assert [d.value for d in second_init.args.kw_defaults] == [0]
891
892 third_init: bases.UnboundMethod = next(third.infer())
893 assert [a.name for a in third_init.args.args] == ["self", "c1", "p2"]
894 assert [a.name for a in third_init.args.kwonlyargs] == ["p1", "p3"]
895 assert [d.value for d in third_init.args.defaults] == [1]
896 assert [d.value for d in third_init.args.kw_defaults] == [0, 2]
897
898
899 def test_dataclass_with_unknown_base() -> None:
900 """Regression test for dataclasses with unknown base classes.
901
902 Reported in https://github.com/pylint-dev/pylint/issues/7418
903 """
904 node = astroid.extract_node("""
905 import dataclasses
906
907 from unknown import Unknown
908
909
910 @dataclasses.dataclass
911 class MyDataclass(Unknown):
912 pass
913
914 MyDataclass()
915 """)
916
917 assert next(node.infer())
918
919
920 def test_dataclass_with_unknown_typing() -> None:
921 """Regression test for dataclasses with unknown base classes.
922
923 Reported in https://github.com/pylint-dev/pylint/issues/7422
924 """
925 node = astroid.extract_node("""
926 from dataclasses import dataclass, InitVar
927
928
929 @dataclass
930 class TestClass:
931 '''Test Class'''
932
933 config: InitVar = None
934
935 TestClass.__init__ #@
936 """)
937
938 init_def: bases.UnboundMethod = next(node.infer())
939 assert [a.name for a in init_def.args.args] == ["self", "config"]
940
941
942 def test_dataclass_with_default_factory() -> None:
943 """Regression test for dataclasses with default values.
944
945 Reported in https://github.com/pylint-dev/pylint/issues/7425
946 """
947 bad_node, good_node = astroid.extract_node("""
948 from dataclasses import dataclass
949 from typing import Union
950
951 @dataclass
952 class BadExampleParentClass:
953 xyz: Union[str, int]
954
955 @dataclass
956 class BadExampleClass(BadExampleParentClass):
957 xyz: str = ""
958
959 BadExampleClass.__init__ #@
960
961 @dataclass
962 class GoodExampleParentClass:
963 xyz: str
964
965 @dataclass
966 class GoodExampleClass(GoodExampleParentClass):
967 xyz: str = ""
968
969 GoodExampleClass.__init__ #@
970 """)
971
972 bad_init: bases.UnboundMethod = next(bad_node.infer())
973 assert bad_init.args.defaults
974 assert [a.name for a in bad_init.args.args] == ["self", "xyz"]
975
976 good_init: bases.UnboundMethod = next(good_node.infer())
977 assert bad_init.args.defaults
978 assert [a.name for a in good_init.args.args] == ["self", "xyz"]
979
980
981 def test_dataclass_with_multiple_inheritance() -> None:
982 """Regression test for dataclasses with multiple inheritance.
983
984 Reported in https://github.com/pylint-dev/pylint/issues/7427
985 Reported in https://github.com/pylint-dev/pylint/issues/7434
986 """
987 first, second, overwritten, overwriting, mixed = astroid.extract_node("""
988 from dataclasses import dataclass
989
990 @dataclass
991 class BaseParent:
992 _abc: int = 1
993
994 @dataclass
995 class AnotherParent:
996 ef: int = 2
997
998 @dataclass
999 class FirstChild(BaseParent, AnotherParent):
1000 ghi: int = 3
1001
1002 @dataclass
1003 class ConvolutedParent(AnotherParent):
1004 '''Convoluted Parent'''
1005
1006 @dataclass
1007 class SecondChild(BaseParent, ConvolutedParent):
1008 jkl: int = 4
1009
1010 @dataclass
1011 class OverwritingParent:
1012 ef: str = "2"
1013
1014 @dataclass
1015 class OverwrittenChild(OverwritingParent, AnotherParent):
1016 '''Overwritten Child'''
1017
1018 @dataclass
1019 class OverwritingChild(BaseParent, AnotherParent):
1020 _abc: float = 1.0
1021 ef: float = 2.0
1022
1023 class NotADataclassParent:
1024 ef: int = 2
1025
1026 @dataclass
1027 class ChildWithMixedParents(BaseParent, NotADataclassParent):
1028 ghi: int = 3
1029
1030 FirstChild.__init__ #@
1031 SecondChild.__init__ #@
1032 OverwrittenChild.__init__ #@
1033 OverwritingChild.__init__ #@
1034 ChildWithMixedParents.__init__ #@
1035 """)
1036
1037 first_init: bases.UnboundMethod = next(first.infer())
1038 assert [a.name for a in first_init.args.args] == ["self", "ef", "_abc", "ghi"]
1039 assert [a.value for a in first_init.args.defaults] == [2, 1, 3]
1040
1041 second_init: bases.UnboundMethod = next(second.infer())
1042 assert [a.name for a in second_init.args.args] == ["self", "ef", "_abc", "jkl"]
1043 assert [a.value for a in second_init.args.defaults] == [2, 1, 4]
1044
1045 overwritten_init: bases.UnboundMethod = next(overwritten.infer())
1046 assert [a.name for a in overwritten_init.args.args] == ["self", "ef"]
1047 assert [a.value for a in overwritten_init.args.defaults] == ["2"]
1048
1049 overwriting_init: bases.UnboundMethod = next(overwriting.infer())
1050 assert [a.name for a in overwriting_init.args.args] == ["self", "ef", "_abc"]
1051 assert [a.value for a in overwriting_init.args.defaults] == [2.0, 1.0]
1052
1053 mixed_init: bases.UnboundMethod = next(mixed.infer())
1054 assert [a.name for a in mixed_init.args.args] == ["self", "_abc", "ghi"]
1055 assert [a.value for a in mixed_init.args.defaults] == [1, 3]
1056
1057 first = astroid.extract_node("""
1058 from dataclasses import dataclass
1059
1060 @dataclass
1061 class BaseParent:
1062 required: bool
1063
1064 @dataclass
1065 class FirstChild(BaseParent):
1066 ...
1067
1068 @dataclass
1069 class SecondChild(BaseParent):
1070 optional: bool = False
1071
1072 @dataclass
1073 class GrandChild(FirstChild, SecondChild):
1074 ...
1075
1076 GrandChild.__init__ #@
1077 """)
1078
1079 first_init: bases.UnboundMethod = next(first.infer())
1080 assert [a.name for a in first_init.args.args] == ["self", "required", "optional"]
1081 assert [a.value for a in first_init.args.defaults] == [False]
1082
1083
1084 @pytest.mark.xfail(reason="Transforms returning Uninferable isn't supported.")
1085 def test_dataclass_non_default_argument_after_default() -> None:
1086 """Test that a non-default argument after a default argument is not allowed.
1087
1088 This should succeed, but the dataclass brain is a transform
1089 which currently can't return an Uninferable correctly. Therefore, we can't
1090 set the dataclass ClassDef node to be Uninferable currently.
1091 Eventually it can be merged into test_dataclass_with_multiple_inheritance.
1092 """
1093
1094 impossible = astroid.extract_node("""
1095 from dataclasses import dataclass
1096
1097 @dataclass
1098 class BaseParent:
1099 required: bool
1100
1101 @dataclass
1102 class FirstChild(BaseParent):
1103 ...
1104
1105 @dataclass
1106 class SecondChild(BaseParent):
1107 optional: bool = False
1108
1109 @dataclass
1110 class ThirdChild:
1111 other: bool = False
1112
1113 @dataclass
1114 class ImpossibleGrandChild(FirstChild, SecondChild, ThirdChild):
1115 ...
1116
1117 ImpossibleGrandChild() #@
1118 """)
1119
1120 assert next(impossible.infer()) is Uninferable
1121
1122
1123 def test_dataclass_with_field_init_is_false() -> None:
1124 """When init=False it shouldn't end up in the __init__."""
1125 first, second, second_child, third_child, third = astroid.extract_node("""
1126 from dataclasses import dataclass, field
1127
1128
1129 @dataclass
1130 class First:
1131 a: int
1132
1133 @dataclass
1134 class Second(First):
1135 a: int = field(init=False, default=1)
1136
1137 @dataclass
1138 class SecondChild(Second):
1139 a: float
1140
1141 @dataclass
1142 class ThirdChild(SecondChild):
1143 a: str
1144
1145 @dataclass
1146 class Third(First):
1147 a: str
1148
1149 First.__init__ #@
1150 Second.__init__ #@
1151 SecondChild.__init__ #@
1152 ThirdChild.__init__ #@
1153 Third.__init__ #@
1154 """)
1155
1156 first_init: bases.UnboundMethod = next(first.infer())
1157 assert [a.name for a in first_init.args.args] == ["self", "a"]
1158 assert [a.value for a in first_init.args.defaults] == []
1159
1160 second_init: bases.UnboundMethod = next(second.infer())
1161 assert [a.name for a in second_init.args.args] == ["self"]
1162 assert [a.value for a in second_init.args.defaults] == []
1163
1164 second_child_init: bases.UnboundMethod = next(second_child.infer())
1165 assert [a.name for a in second_child_init.args.args] == ["self", "a"]
1166 assert [a.value for a in second_child_init.args.defaults] == [1]
1167
1168 third_child_init: bases.UnboundMethod = next(third_child.infer())
1169 assert [a.name for a in third_child_init.args.args] == ["self", "a"]
1170 assert [a.value for a in third_child_init.args.defaults] == [1]
1171
1172 third_init: bases.UnboundMethod = next(third.infer())
1173 assert [a.name for a in third_init.args.args] == ["self", "a"]
1174 assert [a.value for a in third_init.args.defaults] == []
1175
1176
1177 def test_dataclass_inits_of_non_dataclasses() -> None:
1178 """Regression test for __init__ mangling for non dataclasses.
1179
1180 Regression test against changes tested in test_dataclass_with_multiple_inheritance
1181 """
1182 first, second, third = astroid.extract_node("""
1183 from dataclasses import dataclass
1184
1185 @dataclass
1186 class DataclassParent:
1187 _abc: int = 1
1188
1189
1190 class NotADataclassParent:
1191 ef: int = 2
1192
1193
1194 class FirstChild(DataclassParent, NotADataclassParent):
1195 ghi: int = 3
1196
1197
1198 class SecondChild(DataclassParent, NotADataclassParent):
1199 ghi: int = 3
1200
1201 def __init__(self, ef: int = 3):
1202 self.ef = ef
1203
1204
1205 class ThirdChild(NotADataclassParent, DataclassParent):
1206 ghi: int = 3
1207
1208 def __init__(self, ef: int = 3):
1209 self.ef = ef
1210
1211 FirstChild.__init__ #@
1212 SecondChild.__init__ #@
1213 ThirdChild.__init__ #@
1214 """)
1215
1216 first_init: bases.UnboundMethod = next(first.infer())
1217 assert [a.name for a in first_init.args.args] == ["self", "_abc"]
1218 assert [a.value for a in first_init.args.defaults] == [1]
1219
1220 second_init: bases.UnboundMethod = next(second.infer())
1221 assert [a.name for a in second_init.args.args] == ["self", "ef"]
1222 assert [a.value for a in second_init.args.defaults] == [3]
1223
1224 third_init: bases.UnboundMethod = next(third.infer())
1225 assert [a.name for a in third_init.args.args] == ["self", "ef"]
1226 assert [a.value for a in third_init.args.defaults] == [3]
1227
1228
1229 def test_dataclass_with_properties() -> None:
1230 """Tests for __init__ creation for dataclasses that use properties."""
1231 first, second, third = astroid.extract_node("""
1232 from dataclasses import dataclass
1233
1234 @dataclass
1235 class Dataclass:
1236 attr: int
1237
1238 @property
1239 def attr(self) -> int:
1240 return 1
1241
1242 @attr.setter
1243 def attr(self, value: int) -> None:
1244 pass
1245
1246 class ParentOne(Dataclass):
1247 '''Docstring'''
1248
1249 @dataclass
1250 class ParentTwo(Dataclass):
1251 '''Docstring'''
1252
1253 Dataclass.__init__ #@
1254 ParentOne.__init__ #@
1255 ParentTwo.__init__ #@
1256 """)
1257
1258 first_init: bases.UnboundMethod = next(first.infer())
1259 assert [a.name for a in first_init.args.args] == ["self", "attr"]
1260 assert [a.value for a in first_init.args.defaults] == [1]
1261
1262 second_init: bases.UnboundMethod = next(second.infer())
1263 assert [a.name for a in second_init.args.args] == ["self", "attr"]
1264 assert [a.value for a in second_init.args.defaults] == [1]
1265
1266 third_init: bases.UnboundMethod = next(third.infer())
1267 assert [a.name for a in third_init.args.args] == ["self", "attr"]
1268 assert [a.value for a in third_init.args.defaults] == [1]
1269
1270 fourth = astroid.extract_node("""
1271 from dataclasses import dataclass
1272
1273 @dataclass
1274 class Dataclass:
1275 other_attr: str
1276 attr: str
1277
1278 @property
1279 def attr(self) -> str:
1280 return self.other_attr[-1]
1281
1282 @attr.setter
1283 def attr(self, value: int) -> None:
1284 pass
1285
1286 Dataclass.__init__ #@
1287 """)
1288
1289 fourth_init: bases.UnboundMethod = next(fourth.infer())
1290 assert [a.name for a in fourth_init.args.args] == ["self", "other_attr", "attr"]
1291 assert [a.name for a in fourth_init.args.defaults] == ["Uninferable"]
1292
1293
1294 def test_dataclass_with_duplicate_bases_no_crash():
1295 """Regression test for https://github.com/pylint-dev/astroid/issues/2628.
1296
1297 A dataclass inheriting from a class with duplicate bases in MRO
1298 (e.g., Protocol appearing both directly and indirectly) should not
1299 crash with DuplicateBasesError during AST transformation.
1300 """
1301 code = """
1302 import dataclasses
1303 from typing import TypeVar, Protocol
1304
1305 BaseT = TypeVar("BaseT")
1306 T = TypeVar("T", bound=BaseT)
1307
1308 class ConfigBase(Protocol[BaseT]):
1309 ...
1310
1311 class Config(ConfigBase[T], Protocol[T]):
1312 ...
1313
1314 @dataclasses.dataclass
1315 class DatasetConfig(Config[T]):
1316 name: str = "default"
1317
1318 DatasetConfig.__init__ #@
1319 """
1320 node = astroid.extract_node(code)
1321 # Should not raise DuplicateBasesError — graceful degradation instead
1322 inferred = next(node.infer())
1323 assert inferred is not None
1324
1325
1326 def test_dataclass_with_duplicate_bases_field_default():
1327 """Regression test for _get_previous_field_default with broken MRO.
1328
1329 When a parent dataclass defines a field with a default and a child (with
1330 duplicate bases in its MRO) re-annotates that field without a value,
1331 _get_previous_field_default should not crash with DuplicateBasesError.
1332
1333 See https://github.com/pylint-dev/astroid/issues/2628.
1334 """
1335 code = """
1336 import dataclasses
1337 from typing import TypeVar, Protocol
1338
1339 BaseT = TypeVar("BaseT")
1340 T = TypeVar("T", bound=BaseT)
1341
1342 class ConfigBase(Protocol[BaseT]):
1343 ...
1344
1345 class Config(ConfigBase[T], Protocol[T]):
1346 ...
1347
1348 @dataclasses.dataclass
1349 class BaseConfig(Config[T]):
1350 name: str = "default"
1351
1352 @dataclasses.dataclass
1353 class ChildConfig(BaseConfig[T]):
1354 name: str
1355
1356 ChildConfig.__init__ #@
1357 """
1358 node = astroid.extract_node(code)
1359 # Should not raise DuplicateBasesError in _get_previous_field_default
1360 inferred = next(node.infer())
1361 assert inferred is not None
1362
1363
1364 def test_dataclass_base_with_annotated_init_no_crash():
1365 """Regression test for https://github.com/pylint-dev/astroid/issues/3200.
1366
1367 A base dataclass can bind ``__init__`` to something that is not a function
1368 by annotating it as a field. Collecting the arguments of such a base should
1369 not crash with an AttributeError.
1370 """
1371 node = astroid.extract_node("""
1372 from dataclasses import dataclass
1373
1374 @dataclass
1375 class A:
1376 __init__: int
1377
1378 @dataclass
1379 class B(A):
1380 pass
1381
1382 B.__init__ #@
1383 """)
1384
1385 inferred = next(node.infer())
1386 assert isinstance(inferred, bases.UnboundMethod)
1387 assert [a.name for a in inferred.args.args] == ["self"]