Debian Codegraph @

test-data/unit/check-dataclass-transform.test

raw
1 [case testDataclassTransformReusesDataclassLogic]
2 # flags: --python-version 3.11
3 from typing import dataclass_transform, Type
4
5 @dataclass_transform()
6 def my_dataclass(cls: Type) -> Type:
7 return cls
8
9 @my_dataclass
10 class Person:
11 name: str
12 age: int
13
14 def summary(self):
15 return "%s is %d years old." % (self.name, self.age)
16
17 reveal_type(Person) # N: Revealed type is "def (name: builtins.str, age: builtins.int) -> __main__.Person"
18 Person('John', 32)
19 Person('Jonh', 21, None) # E: Too many arguments for "Person"
20
21 [typing fixtures/typing-full.pyi]
22 [builtins fixtures/dataclasses.pyi]
23
24 [case testDataclassTransformIsFoundInTypingExtensions]
25 from typing import Type
26 from typing_extensions import dataclass_transform
27
28 @dataclass_transform()
29 def my_dataclass(cls: Type) -> Type:
30 return cls
31
32 @my_dataclass
33 class Person:
34 name: str
35 age: int
36
37 def summary(self):
38 return "%s is %d years old." % (self.name, self.age)
39
40 reveal_type(Person) # N: Revealed type is "def (name: builtins.str, age: builtins.int) -> __main__.Person"
41 Person('John', 32)
42 Person('Jonh', 21, None) # E: Too many arguments for "Person"
43
44 [typing fixtures/typing-full.pyi]
45 [builtins fixtures/dataclasses.pyi]
46
47 [case testDataclassTransformParametersAreApplied]
48 # flags: --python-version 3.11
49 from typing import dataclass_transform, Callable, Type
50
51 @dataclass_transform()
52 def my_dataclass(*, eq: bool, order: bool) -> Callable[[Type], Type]:
53 def transform(cls: Type) -> Type:
54 return cls
55 return transform
56
57 @my_dataclass(eq=False, order=True) # E: "eq" must be True if "order" is True
58 class Person:
59 name: str
60 age: int
61
62 reveal_type(Person) # N: Revealed type is "def (name: builtins.str, age: builtins.int) -> __main__.Person"
63 Person('John', 32)
64 Person('John', 21, None) # E: Too many arguments for "Person"
65
66 [typing fixtures/typing-full.pyi]
67 [builtins fixtures/dataclasses.pyi]
68
69 [case testDataclassTransformParametersMustBeBoolLiterals]
70 # flags: --python-version 3.11
71 from typing import dataclass_transform, Callable, Type
72
73 @dataclass_transform()
74 def my_dataclass(*, eq: bool = True, order: bool = False) -> Callable[[Type], Type]:
75 def transform(cls: Type) -> Type:
76 return cls
77 return transform
78 @dataclass_transform()
79 class BaseClass:
80 def __init_subclass__(cls, *, eq: bool): ...
81 @dataclass_transform()
82 class Metaclass(type): ...
83
84 BOOL_CONSTANT = True
85 @my_dataclass(eq=BOOL_CONSTANT) # E: "eq" argument must be a True or False literal
86 class A: ...
87 @my_dataclass(order=not False) # E: "order" argument must be a True or False literal
88 class B: ...
89 class C(BaseClass, eq=BOOL_CONSTANT): ... # E: "eq" argument must be a True or False literal
90 class D(metaclass=Metaclass, order=not False): ... # E: "order" argument must be a True or False literal
91
92 [typing fixtures/typing-full.pyi]
93 [builtins fixtures/dataclasses.pyi]
94
95 [case testDataclassTransformDefaultParamsMustBeLiterals]
96 # flags: --python-version 3.11
97 from typing import dataclass_transform, Type, Final
98
99 BOOLEAN_CONSTANT = True
100 FINAL_BOOLEAN: Final = True
101
102 @dataclass_transform(eq_default=BOOLEAN_CONSTANT) # E: "eq_default" argument must be a True or False literal
103 def foo(cls: Type) -> Type:
104 return cls
105 @dataclass_transform(eq_default=(not True)) # E: "eq_default" argument must be a True or False literal
106 def bar(cls: Type) -> Type:
107 return cls
108 @dataclass_transform(eq_default=FINAL_BOOLEAN) # E: "eq_default" argument must be a True or False literal
109 def baz(cls: Type) -> Type:
110 return cls
111
112 [typing fixtures/typing-full.pyi]
113 [builtins fixtures/dataclasses.pyi]
114
115 [case testDataclassTransformUnrecognizedParamsAreErrors]
116 # flags: --python-version 3.11
117 from typing import dataclass_transform, Type
118
119 BOOLEAN_CONSTANT = True
120
121 @dataclass_transform(nonexistent=True) # E: Unrecognized dataclass_transform parameter "nonexistent"
122 def foo(cls: Type) -> Type:
123 return cls
124
125 [typing fixtures/typing-full.pyi]
126 [builtins fixtures/dataclasses.pyi]
127
128
129 [case testDataclassTransformDefaultParams]
130 # flags: --python-version 3.11
131 from typing import dataclass_transform, Type, Callable
132
133 @dataclass_transform(eq_default=False)
134 def no_eq(*, order: bool = False) -> Callable[[Type], Type]:
135 return lambda cls: cls
136 @no_eq()
137 class Foo: ...
138 @no_eq(order=True) # E: "eq" must be True if "order" is True
139 class Bar: ...
140
141
142 @dataclass_transform(kw_only_default=True)
143 def always_use_kw(cls: Type) -> Type:
144 return cls
145 @always_use_kw
146 class Baz:
147 x: int
148 Baz(x=5)
149 Baz(5) # E: Too many positional arguments for "Baz"
150
151 @dataclass_transform(order_default=True)
152 def ordered(*, eq: bool = True) -> Callable[[Type], Type]:
153 return lambda cls: cls
154 @ordered()
155 class A:
156 x: int
157 A(1) > A(2)
158
159 @dataclass_transform(frozen_default=True)
160 def frozen(cls: Type) -> Type:
161 return cls
162 @frozen
163 class B:
164 x: int
165 b = B(x=1)
166 b.x = 2 # E: Property "x" defined in "B" is read-only
167
168 [typing fixtures/typing-full.pyi]
169 [builtins fixtures/dataclasses.pyi]
170
171 [case testDataclassTransformDefaultsCanBeOverridden]
172 # flags: --python-version 3.11
173 from typing import dataclass_transform, Callable, Type
174
175 @dataclass_transform(kw_only_default=True)
176 def my_dataclass(*, kw_only: bool = True) -> Callable[[Type], Type]:
177 return lambda cls: cls
178
179 @my_dataclass()
180 class KwOnly:
181 x: int
182 @my_dataclass(kw_only=False)
183 class KwOptional:
184 x: int
185
186 KwOnly(5) # E: Too many positional arguments for "KwOnly"
187 KwOptional(5)
188
189 [typing fixtures/typing-full.pyi]
190 [builtins fixtures/dataclasses.pyi]
191
192 [case testDataclassTransformFieldSpecifiersDefaultsToEmpty]
193 # flags: --python-version 3.11
194 from dataclasses import field, dataclass
195 from typing import dataclass_transform, Type
196
197 @dataclass_transform()
198 def my_dataclass(cls: Type) -> Type:
199 return cls
200
201 @my_dataclass
202 class Foo:
203 foo: int = field(kw_only=True)
204
205 # Does not cause a type error because `dataclasses.field` is not a recognized field specifier by
206 # default
207 Foo(5)
208
209 [typing fixtures/typing-full.pyi]
210 [builtins fixtures/dataclasses.pyi]
211
212 [case testDataclassTransformFieldSpecifierRejectMalformed]
213 # flags: --python-version 3.11
214 from typing import dataclass_transform, Any, Callable, Final, Type
215
216 def some_type() -> Type: ...
217 def some_function() -> Callable[[], None]: ...
218
219 def field(*args, **kwargs): ...
220 def fields_tuple() -> tuple[type | Callable[..., Any], ...]: return (field,)
221 CONSTANT: Final = (field,)
222
223 @dataclass_transform(field_specifiers=(some_type(),)) # E: "field_specifiers" must only contain identifiers
224 def bad_dataclass1() -> None: ...
225 @dataclass_transform(field_specifiers=(some_function(),)) # E: "field_specifiers" must only contain identifiers
226 def bad_dataclass2() -> None: ...
227 @dataclass_transform(field_specifiers=CONSTANT) # E: "field_specifiers" argument must be a tuple literal
228 def bad_dataclass3() -> None: ...
229 @dataclass_transform(field_specifiers=fields_tuple()) # E: "field_specifiers" argument must be a tuple literal
230 def bad_dataclass4() -> None: ...
231
232 [typing fixtures/typing-full.pyi]
233 [builtins fixtures/dataclasses.pyi]
234
235 [case testDataclassTransformFieldSpecifierParams]
236 # flags: --python-version 3.11
237 from typing import dataclass_transform, Any, Callable, Type, Final
238
239 def field(
240 *,
241 init: bool = True,
242 kw_only: bool = False,
243 alias: str | None = None,
244 default: Any | None = None,
245 default_factory: Callable[[], Any] | None = None,
246 factory: Callable[[], Any] | None = None,
247 ): ...
248 @dataclass_transform(field_specifiers=(field,))
249 def my_dataclass(cls: Type) -> Type:
250 return cls
251
252 B: Final = 'b_'
253 @my_dataclass
254 class Foo:
255 a: int = field(alias='a_')
256 b: int = field(alias=B)
257 # cannot be passed as a positional
258 kwonly: int = field(kw_only=True, default=0)
259 # Safe to omit from constructor, error to pass
260 noinit: int = field(init=False, default=1)
261 # It should be safe to call the constructor without passing any of these
262 unused1: int = field(default=0)
263 unused2: int = field(factory=lambda: 0)
264 unused3: int = field(default_factory=lambda: 0)
265
266 Foo(a=5, b_=1) # E: Unexpected keyword argument "a" for "Foo"
267 Foo(a_=1, b_=1, noinit=1) # E: Unexpected keyword argument "noinit" for "Foo"
268 Foo(1, 2, 3) # (a, b, unused1)
269 foo = Foo(1, 2, kwonly=3)
270 reveal_type(foo.noinit) # N: Revealed type is "builtins.int"
271 reveal_type(foo.unused1) # N: Revealed type is "builtins.int"
272 Foo(a_=5, b_=1, unused1=2, unused2=3, unused3=4)
273
274 def some_str() -> str: ...
275 def some_bool() -> bool: ...
276 @my_dataclass
277 class Bad:
278 bad1: int = field(alias=some_str()) # E: "alias" argument to dataclass field must be a string literal
279 bad2: int = field(kw_only=some_bool()) # E: "kw_only" argument must be a boolean literal
280
281 reveal_type(Foo.__dataclass_fields__) # N: Revealed type is "builtins.dict[builtins.str, Any]"
282
283 [typing fixtures/typing-full.pyi]
284 [builtins fixtures/dataclasses.pyi]
285
286 [case testDataclassTransformFieldSpecifierExtraArgs]
287 # flags: --python-version 3.11
288 from typing import dataclass_transform
289
290 def field(extra1, *, kw_only=False, extra2=0): ...
291 @dataclass_transform(field_specifiers=(field,))
292 def my_dataclass(cls):
293 return cls
294
295 @my_dataclass
296 class Good:
297 a: int = field(5)
298 b: int = field(5, extra2=1)
299 c: int = field(5, kw_only=True)
300
301 @my_dataclass
302 class Bad:
303 a: int = field(kw_only=True) # E: Missing positional argument "extra1" in call to "field"
304
305 [typing fixtures/typing-full.pyi]
306 [builtins fixtures/dataclasses.pyi]
307
308 [case testDataclassTransformMultipleFieldSpecifiers]
309 # flags: --python-version 3.11
310 from typing import dataclass_transform
311
312 def field1(*, default: int) -> int: ...
313 def field2(*, default: str) -> str: ...
314
315 @dataclass_transform(field_specifiers=(field1, field2))
316 def my_dataclass(cls): return cls
317
318 @my_dataclass
319 class Foo:
320 a: int = field1(default=0)
321 b: str = field2(default='hello')
322
323 reveal_type(Foo) # N: Revealed type is "def (a: builtins.int =, b: builtins.str =) -> __main__.Foo"
324 Foo()
325 Foo(a=1, b='bye')
326
327 [typing fixtures/typing-full.pyi]
328 [builtins fixtures/dataclasses.pyi]
329
330 [case testDataclassTransformFieldSpecifierImplicitInit]
331 # flags: --python-version 3.11
332 from typing import dataclass_transform, Literal, overload
333
334 def init(*, init: Literal[True] = True): ...
335 def no_init(*, init: Literal[False] = False): ...
336
337 @overload
338 def field_overload(*, custom: None, init: Literal[True] = True): ...
339 @overload
340 def field_overload(*, custom: str, init: Literal[False] = False): ...
341 def field_overload(*, custom, init): ...
342
343 @dataclass_transform(field_specifiers=(init, no_init, field_overload))
344 def my_dataclass(cls): return cls
345
346 @my_dataclass
347 class Foo:
348 a: int = init()
349 b: int = field_overload(custom=None)
350
351 bad1: int = no_init()
352 bad2: int = field_overload(custom="bad2")
353
354 reveal_type(Foo) # N: Revealed type is "def (a: builtins.int, b: builtins.int) -> __main__.Foo"
355 Foo(a=1, b=2)
356 Foo(a=1, b=2, bad1=0) # E: Unexpected keyword argument "bad1" for "Foo"
357 Foo(a=1, b=2, bad2=0) # E: Unexpected keyword argument "bad2" for "Foo"
358
359 [typing fixtures/typing-full.pyi]
360 [builtins fixtures/dataclasses.pyi]
361
362 [case testDataclassTransformOverloadsDecoratorOnOverload]
363 # flags: --python-version 3.11
364 from typing import dataclass_transform, overload, Any, Callable, Type, Literal
365
366 @overload
367 def my_dataclass(*, foo: str) -> Callable[[Type], Type]: ...
368 @overload
369 @dataclass_transform(frozen_default=True)
370 def my_dataclass(*, foo: int) -> Callable[[Type], Type]: ...
371 def my_dataclass(*, foo: Any) -> Callable[[Type], Type]:
372 return lambda cls: cls
373 @my_dataclass(foo="hello")
374 class A:
375 a: int
376 @my_dataclass(foo=5)
377 class B:
378 b: int
379
380 reveal_type(A) # N: Revealed type is "def (a: builtins.int) -> __main__.A"
381 reveal_type(B) # N: Revealed type is "def (b: builtins.int) -> __main__.B"
382 A(1, "hello") # E: Too many arguments for "A"
383 a = A(1)
384 a.a = 2 # E: Property "a" defined in "A" is read-only
385
386 [typing fixtures/typing-full.pyi]
387 [builtins fixtures/dataclasses.pyi]
388
389 [case testDataclassTransformOverloadsDecoratorOnImpl]
390 # flags: --python-version 3.11
391 from typing import dataclass_transform, overload, Any, Callable, Type, Literal
392
393 @overload
394 def my_dataclass(*, foo: str) -> Callable[[Type], Type]: ...
395 @overload
396 def my_dataclass(*, foo: int) -> Callable[[Type], Type]: ...
397 @dataclass_transform(frozen_default=True)
398 def my_dataclass(*, foo: Any) -> Callable[[Type], Type]:
399 return lambda cls: cls
400 @my_dataclass(foo="hello")
401 class A:
402 a: int
403 @my_dataclass(foo=5)
404 class B:
405 b: int
406
407 reveal_type(A) # N: Revealed type is "def (a: builtins.int) -> __main__.A"
408 reveal_type(B) # N: Revealed type is "def (b: builtins.int) -> __main__.B"
409 A(1, "hello") # E: Too many arguments for "A"
410 a = A(1)
411 a.a = 2 # E: Property "a" defined in "A" is read-only
412
413 [typing fixtures/typing-full.pyi]
414 [builtins fixtures/dataclasses.pyi]
415
416 [case testDataclassTransformViaBaseClass]
417 # flags: --python-version 3.11
418 from typing import dataclass_transform
419
420 @dataclass_transform(frozen_default=True)
421 class Dataclass:
422 def __init_subclass__(cls, *, kw_only: bool = False): ...
423
424 class Person(Dataclass, kw_only=True):
425 name: str
426 age: int
427
428 reveal_type(Person) # N: Revealed type is "def (*, name: builtins.str, age: builtins.int) -> __main__.Person"
429 Person('Jonh', 21) # E: Too many positional arguments for "Person"
430 person = Person(name='John', age=32)
431 person.name = "John Smith" # E: Property "name" defined in "Person" is read-only
432
433 class Contact(Person):
434 email: str
435
436 reveal_type(Contact) # N: Revealed type is "def (email: builtins.str, *, name: builtins.str, age: builtins.int) -> __main__.Contact"
437 Contact('[email protected]', name='John', age=32)
438
439 [typing fixtures/typing-full.pyi]
440 [builtins fixtures/dataclasses.pyi]
441
442 [case testDataclassTransformViaMetaclass]
443 # flags: --python-version 3.11
444 from typing import dataclass_transform
445
446 @dataclass_transform(frozen_default=True)
447 class Dataclass(type): ...
448
449 # Note that PEP 681 states that a class that directly specifies a dataclass_transform-decorated
450 # metaclass should be treated as neither frozen nor unfrozen. For Person to have frozen semantics,
451 # it may not directly specify the metaclass.
452 class BaseDataclass(metaclass=Dataclass): ...
453 class Person(BaseDataclass, kw_only=True):
454 name: str
455 age: int
456
457 reveal_type(Person) # N: Revealed type is "def (*, name: builtins.str, age: builtins.int) -> __main__.Person"
458 Person('Jonh', 21) # E: Too many positional arguments for "Person"
459 person = Person(name='John', age=32)
460 person.name = "John Smith" # E: Property "name" defined in "Person" is read-only
461
462 class Contact(Person):
463 email: str
464
465 reveal_type(Contact) # N: Revealed type is "def (email: builtins.str, *, name: builtins.str, age: builtins.int) -> __main__.Contact"
466 Contact('[email protected]', name='John', age=32)
467
468 [typing fixtures/typing-full.pyi]
469 [builtins fixtures/dataclasses.pyi]
470
471 [case testDataclassTransformViaSubclassOfMetaclass]
472 # flags: --python-version 3.11
473 from typing import dataclass_transform
474
475 @dataclass_transform(frozen_default=True)
476 class BaseMeta(type): ...
477 class SubMeta(BaseMeta): ...
478
479 # MyPy does *not* recognize this as a dataclass because the metaclass is not directly decorated with
480 # dataclass_transform
481 class Foo(metaclass=SubMeta):
482 foo: int
483
484 reveal_type(Foo) # N: Revealed type is "def () -> __main__.Foo"
485 Foo(1) # E: Too many arguments for "Foo"
486
487 [typing fixtures/typing-full.pyi]
488 [builtins fixtures/dataclasses.pyi]
489
490 [case testDataclassTransformTypeCheckingInFunction]
491 # flags: --python-version 3.11
492 from typing import dataclass_transform, Type, TYPE_CHECKING
493
494 @dataclass_transform()
495 def model(cls: Type) -> Type:
496 return cls
497
498 @model
499 class FunctionModel:
500 if TYPE_CHECKING:
501 string_: str
502 integer_: int
503 else:
504 string_: tuple
505 integer_: tuple
506
507 FunctionModel(string_="abc", integer_=1)
508 FunctionModel(string_="abc", integer_=tuple()) # E: Argument "integer_" to "FunctionModel" has incompatible type "tuple[Never, ...]"; expected "int"
509
510 [typing fixtures/typing-full.pyi]
511 [builtins fixtures/dataclasses.pyi]
512
513 [case testDataclassTransformNegatedTypeCheckingInFunction]
514 # flags: --python-version 3.11
515 from typing import dataclass_transform, Type, TYPE_CHECKING
516
517 @dataclass_transform()
518 def model(cls: Type) -> Type:
519 return cls
520
521 @model
522 class FunctionModel:
523 if not TYPE_CHECKING:
524 string_: tuple
525 integer_: tuple
526 else:
527 string_: str
528 integer_: int
529
530 FunctionModel(string_="abc", integer_=1)
531 FunctionModel(string_="abc", integer_=tuple()) # E: Argument "integer_" to "FunctionModel" has incompatible type "tuple[Never, ...]"; expected "int"
532
533 [typing fixtures/typing-full.pyi]
534 [builtins fixtures/dataclasses.pyi]
535
536
537 [case testDataclassTransformTypeCheckingInBaseClass]
538 # flags: --python-version 3.11
539 from typing import dataclass_transform, TYPE_CHECKING
540
541 @dataclass_transform()
542 class ModelBase:
543 ...
544
545 class BaseClassModel(ModelBase):
546 if TYPE_CHECKING:
547 string_: str
548 integer_: int
549 else:
550 string_: tuple
551 integer_: tuple
552
553 BaseClassModel(string_="abc", integer_=1)
554 BaseClassModel(string_="abc", integer_=tuple()) # E: Argument "integer_" to "BaseClassModel" has incompatible type "tuple[Never, ...]"; expected "int"
555
556 [typing fixtures/typing-full.pyi]
557 [builtins fixtures/dataclasses.pyi]
558
559 [case testDataclassTransformNegatedTypeCheckingInBaseClass]
560 # flags: --python-version 3.11
561 from typing import dataclass_transform, TYPE_CHECKING
562
563 @dataclass_transform()
564 class ModelBase:
565 ...
566
567 class BaseClassModel(ModelBase):
568 if not TYPE_CHECKING:
569 string_: tuple
570 integer_: tuple
571 else:
572 string_: str
573 integer_: int
574
575 BaseClassModel(string_="abc", integer_=1)
576 BaseClassModel(string_="abc", integer_=tuple()) # E: Argument "integer_" to "BaseClassModel" has incompatible type "tuple[Never, ...]"; expected "int"
577
578 [typing fixtures/typing-full.pyi]
579 [builtins fixtures/dataclasses.pyi]
580
581 [case testDataclassTransformTypeCheckingInMetaClass]
582 # flags: --python-version 3.11
583 from typing import dataclass_transform, Type, TYPE_CHECKING
584
585 @dataclass_transform()
586 class ModelMeta(type):
587 ...
588
589 class ModelBaseWithMeta(metaclass=ModelMeta):
590 ...
591
592 class MetaClassModel(ModelBaseWithMeta):
593 if TYPE_CHECKING:
594 string_: str
595 integer_: int
596 else:
597 string_: tuple
598 integer_: tuple
599
600 MetaClassModel(string_="abc", integer_=1)
601 MetaClassModel(string_="abc", integer_=tuple()) # E: Argument "integer_" to "MetaClassModel" has incompatible type "tuple[Never, ...]"; expected "int"
602
603 [typing fixtures/typing-full.pyi]
604 [builtins fixtures/dataclasses.pyi]
605
606 [case testDataclassTransformNegatedTypeCheckingInMetaClass]
607 # flags: --python-version 3.11
608 from typing import dataclass_transform, Type, TYPE_CHECKING
609
610 @dataclass_transform()
611 class ModelMeta(type):
612 ...
613
614 class ModelBaseWithMeta(metaclass=ModelMeta):
615 ...
616
617 class MetaClassModel(ModelBaseWithMeta):
618 if not TYPE_CHECKING:
619 string_: tuple
620 integer_: tuple
621 else:
622 string_: str
623 integer_: int
624
625 MetaClassModel(string_="abc", integer_=1)
626 MetaClassModel(string_="abc", integer_=tuple()) # E: Argument "integer_" to "MetaClassModel" has incompatible type "tuple[Never, ...]"; expected "int"
627
628 [typing fixtures/typing-full.pyi]
629 [builtins fixtures/dataclasses.pyi]
630
631 [case testDataclassTransformStaticConditionalAttributes]
632 # flags: --python-version 3.11 --always-true TRUTH
633 from typing import dataclass_transform, Type, TYPE_CHECKING
634
635 TRUTH = False # Is set to --always-true
636
637 @dataclass_transform()
638 def model(cls: Type) -> Type:
639 return cls
640
641 @model
642 class FunctionModel:
643 if TYPE_CHECKING:
644 present_1: int
645 else:
646 skipped_1: int
647 if True: # Mypy does not know if it is True or False, so the block is used
648 present_2: int
649 if False: # Mypy does not know if it is True or False, so the block is used
650 present_3: int
651 if not TRUTH:
652 skipped_2: int
653 else:
654 present_4: int
655
656 FunctionModel(
657 present_1=1,
658 present_2=2,
659 present_3=3,
660 present_4=4,
661 )
662 FunctionModel() # E: Missing positional arguments "present_1", "present_2", "present_3", "present_4" in call to "FunctionModel"
663 FunctionModel( # E: Unexpected keyword argument "skipped_1" for "FunctionModel"
664 present_1=1,
665 present_2=2,
666 present_3=3,
667 present_4=4,
668 skipped_1=5,
669 )
670
671 [typing fixtures/typing-full.pyi]
672 [builtins fixtures/dataclasses.pyi]
673
674
675 [case testDataclassTransformStaticDeterministicConditionalElifAttributes]
676 # flags: --python-version 3.11 --always-true TRUTH --always-false LIE
677 from typing import dataclass_transform, Type, TYPE_CHECKING
678
679 TRUTH = False # Is set to --always-true
680 LIE = True # Is set to --always-false
681
682 @dataclass_transform()
683 def model(cls: Type) -> Type:
684 return cls
685
686 @model
687 class FunctionModel:
688 if TYPE_CHECKING:
689 present_1: int
690 elif TRUTH:
691 skipped_1: int
692 else:
693 skipped_2: int
694 if LIE:
695 skipped_3: int
696 elif TRUTH:
697 present_2: int
698 else:
699 skipped_4: int
700 if LIE:
701 skipped_5: int
702 elif LIE:
703 skipped_6: int
704 else:
705 present_3: int
706
707 FunctionModel(
708 present_1=1,
709 present_2=2,
710 present_3=3,
711 )
712
713 [typing fixtures/typing-full.pyi]
714 [builtins fixtures/dataclasses.pyi]
715
716 [case testDataclassTransformStaticNotDeterministicConditionalElifAttributes]
717 # flags: --python-version 3.11 --always-true TRUTH --always-false LIE
718 from typing import dataclass_transform, Type, TYPE_CHECKING
719
720 TRUTH = False # Is set to --always-true
721 LIE = True # Is set to --always-false
722
723 @dataclass_transform()
724 def model(cls: Type) -> Type:
725 return cls
726
727 @model
728 class FunctionModel:
729 if 123: # Mypy does not know if it is True or False, so this block is used
730 present_1: int
731 elif TRUTH: # Mypy does not know if previous condition is True or False, so it uses also this block
732 present_2: int
733 else: # Previous block is for sure True, so this block is skipped
734 skipped_1: int
735 if 123:
736 present_3: int
737 elif 123:
738 present_4: int
739 else:
740 present_5: int
741 if 123: # Mypy does not know if it is True or False, so this block is used
742 present_6: int
743 elif LIE: # This is for sure False, so the block is skipped used
744 skipped_2: int
745 else: # None of the conditions above for sure True, so this block is used
746 present_7: int
747
748 FunctionModel(
749 present_1=1,
750 present_2=2,
751 present_3=3,
752 present_4=4,
753 present_5=5,
754 present_6=6,
755 present_7=7,
756 )
757
758 [typing fixtures/typing-full.pyi]
759 [builtins fixtures/dataclasses.pyi]
760
761 [case testDataclassTransformFunctionConditionalAttributes]
762 # flags: --python-version 3.11
763 from typing import dataclass_transform, Type
764
765 @dataclass_transform()
766 def model(cls: Type) -> Type:
767 return cls
768
769 def condition() -> bool:
770 return True
771
772 @model
773 class FunctionModel:
774 if condition():
775 x: int
776 y: int
777 z1: int
778 else:
779 x: str # E: Name "x" already defined on line 14
780 y: int # E: Name "y" already defined on line 15
781 z2: int
782
783 FunctionModel(x=1, y=2, z1=3, z2=4)
784
785 [typing fixtures/typing-full.pyi]
786 [builtins fixtures/dataclasses.pyi]
787
788
789 [case testDataclassTransformNegatedFunctionConditionalAttributes]
790 # flags: --python-version 3.11
791 from typing import dataclass_transform, Type
792
793 @dataclass_transform()
794 def model(cls: Type) -> Type:
795 return cls
796
797 def condition() -> bool:
798 return True
799
800 @model
801 class FunctionModel:
802 if not condition():
803 x: int
804 y: int
805 z1: int
806 else:
807 x: str # E: Name "x" already defined on line 14
808 y: int # E: Name "y" already defined on line 15
809 z2: int
810
811 FunctionModel(x=1, y=2, z1=3, z2=4)
812
813 [typing fixtures/typing-full.pyi]
814 [builtins fixtures/dataclasses.pyi]
815
816 [case testDataclassTransformDirectMetaclassNeitherFrozenNorNotFrozen]
817 # flags: --python-version 3.11
818 from typing import dataclass_transform, Type
819
820 @dataclass_transform()
821 class Meta(type): ...
822 class Base(metaclass=Meta):
823 base: int
824 class Foo(Base, frozen=True):
825 foo: int
826 class Bar(Base, frozen=False):
827 bar: int
828
829
830 foo = Foo(0, 1)
831 foo.foo = 5 # E: Property "foo" defined in "Foo" is read-only
832 foo.base = 6
833 reveal_type(foo.base) # N: Revealed type is "builtins.int"
834 bar = Bar(0, 1)
835 bar.bar = 5
836 bar.base = 6
837 reveal_type(bar.base) # N: Revealed type is "builtins.int"
838
839 [typing fixtures/typing-full.pyi]
840 [builtins fixtures/dataclasses.pyi]
841
842 [case testDataclassTransformReplace]
843 from dataclasses import replace
844 from typing import dataclass_transform, Type
845
846 @dataclass_transform()
847 def my_dataclass(cls: Type) -> Type:
848 return cls
849
850 @my_dataclass
851 class Person:
852 name: str
853
854 p = Person('John')
855 y = replace(p, name='Bob')
856
857 [typing fixtures/typing-full.pyi]
858 [builtins fixtures/dataclasses.pyi]
859
860 [case testDataclassTransformSimpleDescriptor]
861 # flags: --python-version 3.11
862
863 from typing import dataclass_transform, overload, Any
864
865 @dataclass_transform()
866 def my_dataclass(cls): ...
867
868 class Desc:
869 @overload
870 def __get__(self, instance: None, owner: Any) -> Desc: ...
871 @overload
872 def __get__(self, instance: object, owner: Any) -> str: ...
873 def __get__(self, instance: object | None, owner: Any) -> Desc | str: ...
874
875 def __set__(self, instance: Any, value: str) -> None: ...
876
877 @my_dataclass
878 class C:
879 x: Desc
880 y: int
881
882 C(x='x', y=1)
883 C(x=1, y=1) # E: Argument "x" to "C" has incompatible type "int"; expected "str"
884 reveal_type(C(x='x', y=1).x) # N: Revealed type is "builtins.str"
885 reveal_type(C(x='x', y=1).y) # N: Revealed type is "builtins.int"
886 reveal_type(C.x) # N: Revealed type is "__main__.Desc"
887
888 [typing fixtures/typing-full.pyi]
889 [builtins fixtures/dataclasses.pyi]
890
891 [case testDataclassTransformUnannotatedDescriptor]
892 # flags: --python-version 3.11
893
894 from typing import dataclass_transform, overload, Any
895
896 @dataclass_transform()
897 def my_dataclass(cls): ...
898
899 class Desc:
900 @overload
901 def __get__(self, instance: None, owner: Any) -> Desc: ...
902 @overload
903 def __get__(self, instance: object, owner: Any) -> str: ...
904 def __get__(self, instance: object | None, owner: Any) -> Desc | str: ...
905
906 def __set__(*args, **kwargs): ...
907
908 @my_dataclass
909 class C:
910 x: Desc
911 y: int
912
913 C(x='x', y=1)
914 C(x=1, y=1)
915 reveal_type(C(x='x', y=1).x) # N: Revealed type is "builtins.str"
916 reveal_type(C(x='x', y=1).y) # N: Revealed type is "builtins.int"
917 reveal_type(C.x) # N: Revealed type is "__main__.Desc"
918
919 [typing fixtures/typing-full.pyi]
920 [builtins fixtures/dataclasses.pyi]
921
922 [case testDataclassTransformGenericDescriptor]
923 # flags: --python-version 3.11
924
925 from typing import dataclass_transform, overload, Any, TypeVar, Generic
926
927 @dataclass_transform()
928 def my_dataclass(frozen: bool = False): ...
929
930 T = TypeVar("T")
931
932 class Desc(Generic[T]):
933 @overload
934 def __get__(self, instance: None, owner: Any) -> Desc[T]: ...
935 @overload
936 def __get__(self, instance: object, owner: Any) -> T: ...
937 def __get__(self, instance: object | None, owner: Any) -> Desc | T: ...
938
939 def __set__(self, instance: Any, value: T) -> None: ...
940
941 @my_dataclass()
942 class C:
943 x: Desc[str]
944
945 C(x='x')
946 C(x=1) # E: Argument "x" to "C" has incompatible type "int"; expected "str"
947 reveal_type(C(x='x').x) # N: Revealed type is "builtins.str"
948 reveal_type(C.x) # N: Revealed type is "__main__.Desc[builtins.str]"
949
950 @my_dataclass()
951 class D(C):
952 y: Desc[int]
953
954 d = D(x='x', y=1)
955 reveal_type(d.x) # N: Revealed type is "builtins.str"
956 reveal_type(d.y) # N: Revealed type is "builtins.int"
957 reveal_type(D.x) # N: Revealed type is "__main__.Desc[builtins.str]"
958 reveal_type(D.y) # N: Revealed type is "__main__.Desc[builtins.int]"
959
960 @my_dataclass(frozen=True)
961 class F:
962 x: Desc[str] = Desc()
963
964 F(x='x')
965 F(x=1) # E: Argument "x" to "F" has incompatible type "int"; expected "str"
966 reveal_type(F(x='x').x) # N: Revealed type is "builtins.str"
967 reveal_type(F.x) # N: Revealed type is "__main__.Desc[builtins.str]"
968
969 [typing fixtures/typing-full.pyi]
970 [builtins fixtures/dataclasses.pyi]
971
972 [case testDataclassTransformGenericDescriptorWithInheritance]
973 # flags: --python-version 3.11
974
975 from typing import dataclass_transform, overload, Any, TypeVar, Generic
976
977 @dataclass_transform()
978 def my_dataclass(cls): ...
979
980 T = TypeVar("T")
981
982 class Desc(Generic[T]):
983 @overload
984 def __get__(self, instance: None, owner: Any) -> Desc[T]: ...
985 @overload
986 def __get__(self, instance: object, owner: Any) -> T: ...
987 def __get__(self, instance: object | None, owner: Any) -> Desc | T: ...
988
989 def __set__(self, instance: Any, value: T) -> None: ...
990
991 class Desc2(Desc[str]):
992 pass
993
994 @my_dataclass
995 class C:
996 x: Desc2
997
998 C(x='x')
999 C(x=1) # E: Argument "x" to "C" has incompatible type "int"; expected "str"
1000 reveal_type(C(x='x').x) # N: Revealed type is "builtins.str"
1001 reveal_type(C.x) # N: Revealed type is "__main__.Desc[builtins.str]"
1002
1003 [typing fixtures/typing-full.pyi]
1004 [builtins fixtures/dataclasses.pyi]
1005
1006 [case testDataclassTransformDescriptorWithDifferentGetSetTypes]
1007 # flags: --python-version 3.11
1008
1009 from typing import dataclass_transform, overload, Any
1010
1011 @dataclass_transform()
1012 def my_dataclass(cls): ...
1013
1014 class Desc:
1015 @overload
1016 def __get__(self, instance: None, owner: Any) -> int: ...
1017 @overload
1018 def __get__(self, instance: object, owner: Any) -> str: ...
1019 def __get__(self, instance, owner): ...
1020
1021 def __set__(self, instance: Any, value: bytes | None) -> None: ...
1022
1023 @my_dataclass
1024 class C:
1025 x: Desc
1026
1027 c = C(x=b'x')
1028 c = C(x=None)
1029 C(x=1) # E: Argument "x" to "C" has incompatible type "int"; expected "bytes | None"
1030 reveal_type(c.x) # N: Revealed type is "builtins.str"
1031 reveal_type(C.x) # N: Revealed type is "builtins.int"
1032 c.x = b'x'
1033 c.x = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "bytes | None")
1034
1035 [typing fixtures/typing-full.pyi]
1036 [builtins fixtures/dataclasses.pyi]
1037
1038 [case testDataclassTransformUnsupportedDescriptors]
1039 # flags: --python-version 3.11
1040
1041 from typing import dataclass_transform, overload, Any
1042
1043 @dataclass_transform()
1044 def my_dataclass(cls): ...
1045
1046 class Desc:
1047 @overload
1048 def __get__(self, instance: None, owner: Any) -> int: ...
1049 @overload
1050 def __get__(self, instance: object, owner: Any) -> str: ...
1051 def __get__(self, instance, owner): ...
1052
1053 def __set__(*args, **kwargs) -> None: ...
1054
1055 class Desc2:
1056 @overload
1057 def __get__(self, instance: None, owner: Any) -> int: ...
1058 @overload
1059 def __get__(self, instance: object, owner: Any) -> str: ...
1060 def __get__(self, instance, owner): ...
1061
1062 @overload
1063 def __set__(self, instance: Any, value: bytes) -> None: ...
1064 @overload
1065 def __set__(self) -> None: ...
1066 def __set__(self, *args, **kawrga) -> None: ...
1067
1068 @my_dataclass
1069 class C:
1070 x: Desc # E: Unsupported signature for "__set__" in "Desc"
1071 y: Desc2 # E: Unsupported "__set__" in "Desc2"
1072
1073 [typing fixtures/typing-full.pyi]
1074 [builtins fixtures/dataclasses.pyi]