1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
|
import pytest
import astroid
from astroid import bases, nodes
from astroid.const import PY37_PLUS
from astroid.exceptions import InferenceError
from astroid.util import Uninferable
if not PY37_PLUS:
pytest.skip("Dataclasses were added in 3.7", allow_module_level=True)
parametrize_module = pytest.mark.parametrize(
("module",), (["dataclasses"], ["pydantic.dataclasses"], ["marshmallow_dataclass"])
)
@parametrize_module
def test_inference_attribute_no_default(module: str):
"""Test inference of dataclass attribute with no default.
Note that the argument to the constructor is ignored by the inference.
"""
klass, instance = astroid.extract_node(
f"""
from {module} import dataclass
@dataclass
class A:
name: str
A.name #@
A('hi').name #@
"""
)
with pytest.raises(InferenceError):
klass.inferred()
inferred = instance.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], bases.Instance)
assert inferred[0].name == "str"
@parametrize_module
def test_inference_non_field_default(module: str):
"""Test inference of dataclass attribute with a non-field default."""
klass, instance = astroid.extract_node(
f"""
from {module} import dataclass
@dataclass
class A:
name: str = 'hi'
A.name #@
A().name #@
"""
)
inferred = klass.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.Const)
assert inferred[0].value == "hi"
inferred = instance.inferred()
assert len(inferred) == 2
assert isinstance(inferred[0], nodes.Const)
assert inferred[0].value == "hi"
assert isinstance(inferred[1], bases.Instance)
assert inferred[1].name == "str"
@parametrize_module
def test_inference_field_default(module: str):
"""Test inference of dataclass attribute with a field call default
(default keyword argument given)."""
klass, instance = astroid.extract_node(
f"""
from {module} import dataclass
from dataclasses import field
@dataclass
class A:
name: str = field(default='hi')
A.name #@
A().name #@
"""
)
inferred = klass.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.Const)
assert inferred[0].value == "hi"
inferred = instance.inferred()
assert len(inferred) == 2
assert isinstance(inferred[0], nodes.Const)
assert inferred[0].value == "hi"
assert isinstance(inferred[1], bases.Instance)
assert inferred[1].name == "str"
@parametrize_module
def test_inference_field_default_factory(module: str):
"""Test inference of dataclass attribute with a field call default
(default_factory keyword argument given)."""
klass, instance = astroid.extract_node(
f"""
from {module} import dataclass
from dataclasses import field
@dataclass
class A:
name: list = field(default_factory=list)
A.name #@
A().name #@
"""
)
inferred = klass.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.List)
assert inferred[0].elts == []
inferred = instance.inferred()
assert len(inferred) == 2
assert isinstance(inferred[0], nodes.List)
assert inferred[0].elts == []
assert isinstance(inferred[1], bases.Instance)
assert inferred[1].name == "list"
@parametrize_module
def test_inference_method(module: str):
"""Test inference of dataclass attribute within a method,
with a default_factory field.
Based on https://github.com/PyCQA/pylint/issues/2600
"""
node = astroid.extract_node(
f"""
from typing import Dict
from {module} import dataclass
from dataclasses import field
@dataclass
class TestClass:
foo: str
bar: str
baz_dict: Dict[str, str] = field(default_factory=dict)
def some_func(self) -> None:
f = self.baz_dict.items #@
for key, value in f():
print(key)
print(value)
"""
)
inferred = next(node.value.infer())
assert isinstance(inferred, bases.BoundMethod)
@parametrize_module
def test_inference_no_annotation(module: str):
"""Test that class variables without type annotations are not
turned into instance attributes.
"""
class_def, klass, instance = astroid.extract_node(
f"""
from {module} import dataclass
@dataclass
class A:
name = 'hi'
A #@
A.name #@
A().name #@
"""
)
inferred = next(class_def.infer())
assert isinstance(inferred, nodes.ClassDef)
assert inferred.instance_attrs == {}
# Both the class and instance can still access the attribute
for node in (klass, instance):
assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.Const)
assert inferred[0].value == "hi"
@parametrize_module
def test_inference_class_var(module: str):
"""Test that class variables with a ClassVar type annotations are not
turned into instance attributes.
"""
class_def, klass, instance = astroid.extract_node(
f"""
from {module} import dataclass
from typing import ClassVar
@dataclass
class A:
name: ClassVar[str] = 'hi'
A #@
A.name #@
A().name #@
"""
)
inferred = next(class_def.infer())
assert isinstance(inferred, nodes.ClassDef)
assert inferred.instance_attrs == {}
# Both the class and instance can still access the attribute
for node in (klass, instance):
assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.Const)
assert inferred[0].value == "hi"
@parametrize_module
def test_inference_init_var(module: str):
"""Test that class variables with InitVar type annotations are not
turned into instance attributes.
"""
class_def, klass, instance = astroid.extract_node(
f"""
from {module} import dataclass
from dataclasses import InitVar
@dataclass
class A:
name: InitVar[str] = 'hi'
A #@
A.name #@
A().name #@
"""
)
inferred = next(class_def.infer())
assert isinstance(inferred, nodes.ClassDef)
assert inferred.instance_attrs == {}
# Both the class and instance can still access the attribute
for node in (klass, instance):
assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.Const)
assert inferred[0].value == "hi"
@parametrize_module
def test_inference_generic_collection_attribute(module: str):
"""Test that an attribute with a generic collection type from the
typing module is inferred correctly.
"""
attr_nodes = astroid.extract_node(
f"""
from {module} import dataclass
from dataclasses import field
import typing
@dataclass
class A:
dict_prop: typing.Dict[str, str]
frozenset_prop: typing.FrozenSet[str]
list_prop: typing.List[str]
set_prop: typing.Set[str]
tuple_prop: typing.Tuple[int, str]
a = A({{}}, frozenset(), [], set(), (1, 'hi'))
a.dict_prop #@
a.frozenset_prop #@
a.list_prop #@
a.set_prop #@
a.tuple_prop #@
"""
)
names = (
"Dict",
"FrozenSet",
"List",
"Set",
"Tuple",
)
for node, name in zip(attr_nodes, names):
inferred = next(node.infer())
assert isinstance(inferred, bases.Instance)
assert inferred.name == name
@pytest.mark.parametrize(
("module", "typing_module"),
[
("dataclasses", "typing"),
("pydantic.dataclasses", "typing"),
("pydantic.dataclasses", "collections.abc"),
("marshmallow_dataclass", "typing"),
("marshmallow_dataclass", "collections.abc"),
],
)
def test_inference_callable_attribute(module: str, typing_module: str):
"""Test that an attribute with a Callable annotation is inferred as Uninferable.
See issue #1129 and PyCQA/pylint#4895
"""
instance = astroid.extract_node(
f"""
from {module} import dataclass
from {typing_module} import Any, Callable
@dataclass
class A:
enabled: Callable[[Any], bool]
A(lambda x: x == 42).enabled #@
"""
)
inferred = next(instance.infer())
assert inferred is Uninferable
@parametrize_module
def test_inference_inherited(module: str):
"""Test that an attribute is inherited from a superclass dataclass."""
klass1, instance1, klass2, instance2 = astroid.extract_node(
f"""
from {module} import dataclass
@dataclass
class A:
value: int
name: str = "hi"
@dataclass
class B(A):
new_attr: bool = True
B.value #@
B(1).value #@
B.name #@
B(1).name #@
"""
)
with pytest.raises(InferenceError): # B.value is not defined
klass1.inferred()
inferred = instance1.inferred()
assert isinstance(inferred[0], bases.Instance)
assert inferred[0].name == "int"
inferred = klass2.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.Const)
assert inferred[0].value == "hi"
inferred = instance2.inferred()
assert len(inferred) == 2
assert isinstance(inferred[0], nodes.Const)
assert inferred[0].value == "hi"
assert isinstance(inferred[1], bases.Instance)
assert inferred[1].name == "str"
def test_pydantic_field() -> None:
"""Test that pydantic.Field attributes are currently Uninferable.
(Eventually, we can extend the brain to support pydantic.Field)
"""
klass, instance = astroid.extract_node(
"""
from pydantic import Field
from pydantic.dataclasses import dataclass
@dataclass
class A:
name: str = Field("hi")
A.name #@
A().name #@
"""
)
inferred = klass.inferred()
assert len(inferred) == 1
assert inferred[0] is Uninferable
inferred = instance.inferred()
assert len(inferred) == 2
assert inferred[0] is Uninferable
assert isinstance(inferred[1], bases.Instance)
assert inferred[1].name == "str"
@parametrize_module
def test_init_empty(module: str):
"""Test init for a dataclass with no attributes"""
node = astroid.extract_node(
f"""
from {module} import dataclass
@dataclass
class A:
pass
A.__init__ #@
"""
)
init = next(node.infer())
assert [a.name for a in init.args.args] == ["self"]
@parametrize_module
def test_init_no_defaults(module: str):
"""Test init for a dataclass with attributes and no defaults"""
node = astroid.extract_node(
f"""
from {module} import dataclass
from typing import List
@dataclass
class A:
x: int
y: str
z: List[bool]
A.__init__ #@
"""
)
init = next(node.infer())
assert [a.name for a in init.args.args] == ["self", "x", "y", "z"]
assert [a.as_string() if a else None for a in init.args.annotations] == [
None,
"int",
"str",
"List[bool]",
]
@parametrize_module
def test_init_defaults(module: str):
"""Test init for a dataclass with attributes and some defaults"""
node = astroid.extract_node(
f"""
from {module} import dataclass
from dataclasses import field
from typing import List
@dataclass
class A:
w: int
x: int = 10
y: str = field(default="hi")
z: List[bool] = field(default_factory=list)
A.__init__ #@
"""
)
init = next(node.infer())
assert [a.name for a in init.args.args] == ["self", "w", "x", "y", "z"]
assert [a.as_string() if a else None for a in init.args.annotations] == [
None,
"int",
"int",
"str",
"List[bool]",
]
assert [a.as_string() if a else None for a in init.args.defaults] == [
"10",
"'hi'",
"_HAS_DEFAULT_FACTORY",
]
@parametrize_module
def test_init_initvar(module: str):
"""Test init for a dataclass with attributes and an InitVar"""
node = astroid.extract_node(
f"""
from {module} import dataclass
from dataclasses import InitVar
from typing import List
@dataclass
class A:
x: int
y: str
init_var: InitVar[int]
z: List[bool]
A.__init__ #@
"""
)
init = next(node.infer())
assert [a.name for a in init.args.args] == ["self", "x", "y", "init_var", "z"]
assert [a.as_string() if a else None for a in init.args.annotations] == [
None,
"int",
"str",
"int",
"List[bool]",
]
@parametrize_module
def test_init_decorator_init_false(module: str):
"""Test that no init is generated when init=False is passed to
dataclass decorator.
"""
node = astroid.extract_node(
f"""
from {module} import dataclass
from typing import List
@dataclass(init=False)
class A:
x: int
y: str
z: List[bool]
A.__init__ #@
"""
)
init = next(node.infer())
assert init._proxied.parent.name == "object"
@parametrize_module
def test_init_field_init_false(module: str):
"""Test init for a dataclass with attributes with a field value where init=False
(these attributes should not be included in the initializer).
"""
node = astroid.extract_node(
f"""
from {module} import dataclass
from dataclasses import field
from typing import List
@dataclass
class A:
x: int
y: str
z: List[bool] = field(init=False)
A.__init__ #@
"""
)
init = next(node.infer())
assert [a.name for a in init.args.args] == ["self", "x", "y"]
assert [a.as_string() if a else None for a in init.args.annotations] == [
None,
"int",
"str",
]
@parametrize_module
def test_init_override(module: str):
"""Test init for a dataclass overrides a superclass initializer.
Based on https://github.com/PyCQA/pylint/issues/3201
"""
node = astroid.extract_node(
f"""
from {module} import dataclass
from typing import List
class A:
arg0: str = None
def __init__(self, arg0):
raise NotImplementedError
@dataclass
class B(A):
arg1: int = None
arg2: str = None
B.__init__ #@
"""
)
init = next(node.infer())
assert [a.name for a in init.args.args] == ["self", "arg1", "arg2"]
assert [a.as_string() if a else None for a in init.args.annotations] == [
None,
"int",
"str",
]
@parametrize_module
def test_init_attributes_from_superclasses(module: str):
"""Test init for a dataclass that inherits and overrides attributes from superclasses.
Based on https://github.com/PyCQA/pylint/issues/3201
"""
node = astroid.extract_node(
f"""
from {module} import dataclass
from typing import List
@dataclass
class A:
arg0: float
arg2: str
@dataclass
class B(A):
arg1: int
arg2: list # Overrides arg2 from A
B.__init__ #@
"""
)
init = next(node.infer())
assert [a.name for a in init.args.args] == ["self", "arg0", "arg2", "arg1"]
assert [a.as_string() if a else None for a in init.args.annotations] == [
None,
"float",
"list", # not str
"int",
]
@parametrize_module
def test_invalid_init(module: str):
"""Test that astroid doesn't generate an initializer when attribute order is invalid."""
node = astroid.extract_node(
f"""
from {module} import dataclass
@dataclass
class A:
arg1: float = 0.0
arg2: str
A.__init__ #@
"""
)
init = next(node.infer())
assert init._proxied.parent.name == "object"
@parametrize_module
def test_annotated_enclosed_field_call(module: str):
"""Test inference of dataclass attribute with a field call in another function call"""
node = astroid.extract_node(
f"""
from {module} import dataclass, field
from typing import cast
@dataclass
class A:
attribute: int = cast(int, field(default_factory=dict))
"""
)
inferred = node.inferred()
assert len(inferred) == 1 and isinstance(inferred[0], nodes.ClassDef)
assert "attribute" in inferred[0].instance_attrs
@parametrize_module
def test_invalid_field_call(module: str) -> None:
"""Test inference of invalid field call doesn't crash."""
code = astroid.extract_node(
f"""
from {module} import dataclass, field
@dataclass
class A:
val: field()
"""
)
inferred = code.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.ClassDef)
|