← Back to index

dataclasses_transform_func.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 6
FP: 0
FN: 0
Optional: 0 / 0
1"""
2Tests the dataclass_transform mechanism when it is applied to a decorator function.
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#the-dataclass-transform-decorator
6
7from typing import Any, Callable, TypeVar, dataclass_transform, overload
8
9T = TypeVar("T")
12@overload
13@dataclass_transform(kw_only_default=True, order_default=True)
14def create_model(cls: T) -> T:
15 ...
18@overload
19def create_model(
20 *,
21 frozen: bool = False,
22 kw_only: bool = True,
23 order: bool = True,
24) -> Callable[[T], T]:
25 ...
28def create_model(*args: Any, **kwargs: Any) -> Any:
29 ...
32@create_model(kw_only=False, order=False)
33class Customer1:
34 id: int
35 name: str
38@create_model(frozen=True)
39class Customer2:
40 id: int
41 name: str
44@create_model(frozen=True)
45class Customer2Subclass(Customer2):
46 salary: float
49c1_1 = Customer1(id=3, name="Sue")
50c1_1.id = 4
52c1_2 = Customer1(3, "Sue")
53c1_2.name = "Susan"
55# This should generate an error because of a type mismatch.
56c1_2.name = 3 # E
[invalid-assignment] Object of type `Literal[3]` is not assignable to attribute `name` of type `str`
58# This should generate an error because comparison methods are
59# not synthesized.
60v1 = c1_1 < c1_2 # E
[unsupported-operator] Operator `<` is not supported between two objects of type `Customer1`
62# This should generate an error because salary is not
63# a defined field.
64c1_3 = Customer1(id=3, name="Sue", salary=40000) # E
[unknown-argument] Argument `salary` does not match any known parameter
66c2_1 = Customer2(id=0, name="John")
68# This should generate an error because Customer2 supports
69# keyword-only parameters for its constructor.
70c2_2 = Customer2(0, "John") # E
[missing-argument] No arguments provided for required parameters `id`, `name` [too-many-positional-arguments] Too many positional arguments: expected 0, got 2
72v2 = c2_1 < c2_2
75@dataclass_transform(kw_only_default=True, order_default=True, frozen_default=True)
76def create_model_frozen(cls: T) -> T:
77 raise NotImplementedError
80@create_model_frozen
81class Customer3:
82 id: int
83 name: str
86# This should generate an error because a non-frozen class
87# cannot inherit from a frozen class.
88@create_model # E[Customer3Subclass]
89class Customer3Subclass(Customer3): # E[Customer3Subclass]
Tag 'Customer3Subclass' [invalid-frozen-dataclass-subclass] Non-frozen dataclass `Customer3Subclass` cannot inherit from frozen dataclass `Customer3`
90 age: int
93c3_1 = Customer3(id=2, name="hi")
95# This should generate an error because Customer3 is frozen.
96c3_1.id = 4 # E
[invalid-assignment] Property `id` defined in `Customer3` is read-only