dataclasses.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  1. """Plugin that provides support for dataclasses."""
  2. from __future__ import annotations
  3. from typing import TYPE_CHECKING, Final, Iterator, Literal
  4. from mypy import errorcodes, message_registry
  5. from mypy.expandtype import expand_type, expand_type_by_instance
  6. from mypy.meet import meet_types
  7. from mypy.messages import format_type_bare
  8. from mypy.nodes import (
  9. ARG_NAMED,
  10. ARG_NAMED_OPT,
  11. ARG_OPT,
  12. ARG_POS,
  13. ARG_STAR,
  14. ARG_STAR2,
  15. MDEF,
  16. Argument,
  17. AssignmentStmt,
  18. Block,
  19. CallExpr,
  20. ClassDef,
  21. Context,
  22. DataclassTransformSpec,
  23. Expression,
  24. FuncDef,
  25. FuncItem,
  26. IfStmt,
  27. JsonDict,
  28. NameExpr,
  29. Node,
  30. PlaceholderNode,
  31. RefExpr,
  32. Statement,
  33. SymbolTableNode,
  34. TempNode,
  35. TypeAlias,
  36. TypeInfo,
  37. TypeVarExpr,
  38. Var,
  39. )
  40. from mypy.plugin import ClassDefContext, FunctionSigContext, SemanticAnalyzerPluginInterface
  41. from mypy.plugins.common import (
  42. _get_callee_type,
  43. _get_decorator_bool_argument,
  44. add_attribute_to_class,
  45. add_method_to_class,
  46. deserialize_and_fixup_type,
  47. )
  48. from mypy.semanal_shared import find_dataclass_transform_spec, require_bool_literal_argument
  49. from mypy.server.trigger import make_wildcard_trigger
  50. from mypy.state import state
  51. from mypy.typeops import map_type_from_supertype, try_getting_literals_from_type
  52. from mypy.types import (
  53. AnyType,
  54. CallableType,
  55. FunctionLike,
  56. Instance,
  57. LiteralType,
  58. NoneType,
  59. ProperType,
  60. TupleType,
  61. Type,
  62. TypeOfAny,
  63. TypeVarType,
  64. UninhabitedType,
  65. UnionType,
  66. get_proper_type,
  67. )
  68. from mypy.typevars import fill_typevars
  69. if TYPE_CHECKING:
  70. from mypy.checker import TypeChecker
  71. # The set of decorators that generate dataclasses.
  72. dataclass_makers: Final = {"dataclass", "dataclasses.dataclass"}
  73. SELF_TVAR_NAME: Final = "_DT"
  74. _TRANSFORM_SPEC_FOR_DATACLASSES: Final = DataclassTransformSpec(
  75. eq_default=True,
  76. order_default=False,
  77. kw_only_default=False,
  78. frozen_default=False,
  79. field_specifiers=("dataclasses.Field", "dataclasses.field"),
  80. )
  81. _INTERNAL_REPLACE_SYM_NAME: Final = "__mypy-replace"
  82. _INTERNAL_POST_INIT_SYM_NAME: Final = "__mypy-post_init"
  83. class DataclassAttribute:
  84. def __init__(
  85. self,
  86. name: str,
  87. alias: str | None,
  88. is_in_init: bool,
  89. is_init_var: bool,
  90. has_default: bool,
  91. line: int,
  92. column: int,
  93. type: Type | None,
  94. info: TypeInfo,
  95. kw_only: bool,
  96. is_neither_frozen_nor_nonfrozen: bool,
  97. api: SemanticAnalyzerPluginInterface,
  98. ) -> None:
  99. self.name = name
  100. self.alias = alias
  101. self.is_in_init = is_in_init
  102. self.is_init_var = is_init_var
  103. self.has_default = has_default
  104. self.line = line
  105. self.column = column
  106. self.type = type # Type as __init__ argument
  107. self.info = info
  108. self.kw_only = kw_only
  109. self.is_neither_frozen_nor_nonfrozen = is_neither_frozen_nor_nonfrozen
  110. self._api = api
  111. def to_argument(
  112. self, current_info: TypeInfo, *, of: Literal["__init__", "replace", "__post_init__"]
  113. ) -> Argument:
  114. if of == "__init__":
  115. arg_kind = ARG_POS
  116. if self.kw_only and self.has_default:
  117. arg_kind = ARG_NAMED_OPT
  118. elif self.kw_only and not self.has_default:
  119. arg_kind = ARG_NAMED
  120. elif not self.kw_only and self.has_default:
  121. arg_kind = ARG_OPT
  122. elif of == "replace":
  123. arg_kind = ARG_NAMED if self.is_init_var and not self.has_default else ARG_NAMED_OPT
  124. elif of == "__post_init__":
  125. # We always use `ARG_POS` without a default value, because it is practical.
  126. # Consider this case:
  127. #
  128. # @dataclass
  129. # class My:
  130. # y: dataclasses.InitVar[str] = 'a'
  131. # def __post_init__(self, y: str) -> None: ...
  132. #
  133. # We would be *required* to specify `y: str = ...` if default is added here.
  134. # But, most people won't care about adding default values to `__post_init__`,
  135. # because it is not designed to be called directly, and duplicating default values
  136. # for the sake of type-checking is unpleasant.
  137. arg_kind = ARG_POS
  138. return Argument(
  139. variable=self.to_var(current_info),
  140. type_annotation=self.expand_type(current_info),
  141. initializer=None,
  142. kind=arg_kind,
  143. )
  144. def expand_type(self, current_info: TypeInfo) -> Type | None:
  145. if self.type is not None and self.info.self_type is not None:
  146. # In general, it is not safe to call `expand_type()` during semantic analyzis,
  147. # however this plugin is called very late, so all types should be fully ready.
  148. # Also, it is tricky to avoid eager expansion of Self types here (e.g. because
  149. # we serialize attributes).
  150. with state.strict_optional_set(self._api.options.strict_optional):
  151. return expand_type(
  152. self.type, {self.info.self_type.id: fill_typevars(current_info)}
  153. )
  154. return self.type
  155. def to_var(self, current_info: TypeInfo) -> Var:
  156. return Var(self.alias or self.name, self.expand_type(current_info))
  157. def serialize(self) -> JsonDict:
  158. assert self.type
  159. return {
  160. "name": self.name,
  161. "alias": self.alias,
  162. "is_in_init": self.is_in_init,
  163. "is_init_var": self.is_init_var,
  164. "has_default": self.has_default,
  165. "line": self.line,
  166. "column": self.column,
  167. "type": self.type.serialize(),
  168. "kw_only": self.kw_only,
  169. "is_neither_frozen_nor_nonfrozen": self.is_neither_frozen_nor_nonfrozen,
  170. }
  171. @classmethod
  172. def deserialize(
  173. cls, info: TypeInfo, data: JsonDict, api: SemanticAnalyzerPluginInterface
  174. ) -> DataclassAttribute:
  175. data = data.copy()
  176. typ = deserialize_and_fixup_type(data.pop("type"), api)
  177. return cls(type=typ, info=info, **data, api=api)
  178. def expand_typevar_from_subtype(self, sub_type: TypeInfo) -> None:
  179. """Expands type vars in the context of a subtype when an attribute is inherited
  180. from a generic super type."""
  181. if self.type is not None:
  182. with state.strict_optional_set(self._api.options.strict_optional):
  183. self.type = map_type_from_supertype(self.type, sub_type, self.info)
  184. class DataclassTransformer:
  185. """Implement the behavior of @dataclass.
  186. Note that this may be executed multiple times on the same class, so
  187. everything here must be idempotent.
  188. This runs after the main semantic analysis pass, so you can assume that
  189. there are no placeholders.
  190. """
  191. def __init__(
  192. self,
  193. cls: ClassDef,
  194. # Statement must also be accepted since class definition itself may be passed as the reason
  195. # for subclass/metaclass-based uses of `typing.dataclass_transform`
  196. reason: Expression | Statement,
  197. spec: DataclassTransformSpec,
  198. api: SemanticAnalyzerPluginInterface,
  199. ) -> None:
  200. self._cls = cls
  201. self._reason = reason
  202. self._spec = spec
  203. self._api = api
  204. def transform(self) -> bool:
  205. """Apply all the necessary transformations to the underlying
  206. dataclass so as to ensure it is fully type checked according
  207. to the rules in PEP 557.
  208. """
  209. info = self._cls.info
  210. attributes = self.collect_attributes()
  211. if attributes is None:
  212. # Some definitions are not ready. We need another pass.
  213. return False
  214. for attr in attributes:
  215. if attr.type is None:
  216. return False
  217. decorator_arguments = {
  218. "init": self._get_bool_arg("init", True),
  219. "eq": self._get_bool_arg("eq", self._spec.eq_default),
  220. "order": self._get_bool_arg("order", self._spec.order_default),
  221. "frozen": self._get_bool_arg("frozen", self._spec.frozen_default),
  222. "slots": self._get_bool_arg("slots", False),
  223. "match_args": self._get_bool_arg("match_args", True),
  224. }
  225. py_version = self._api.options.python_version
  226. # If there are no attributes, it may be that the semantic analyzer has not
  227. # processed them yet. In order to work around this, we can simply skip generating
  228. # __init__ if there are no attributes, because if the user truly did not define any,
  229. # then the object default __init__ with an empty signature will be present anyway.
  230. if (
  231. decorator_arguments["init"]
  232. and ("__init__" not in info.names or info.names["__init__"].plugin_generated)
  233. and attributes
  234. ):
  235. args = [
  236. attr.to_argument(info, of="__init__")
  237. for attr in attributes
  238. if attr.is_in_init and not self._is_kw_only_type(attr.type)
  239. ]
  240. if info.fallback_to_any:
  241. # Make positional args optional since we don't know their order.
  242. # This will at least allow us to typecheck them if they are called
  243. # as kwargs
  244. for arg in args:
  245. if arg.kind == ARG_POS:
  246. arg.kind = ARG_OPT
  247. nameless_var = Var("")
  248. args = [
  249. Argument(nameless_var, AnyType(TypeOfAny.explicit), None, ARG_STAR),
  250. *args,
  251. Argument(nameless_var, AnyType(TypeOfAny.explicit), None, ARG_STAR2),
  252. ]
  253. add_method_to_class(
  254. self._api, self._cls, "__init__", args=args, return_type=NoneType()
  255. )
  256. if (
  257. decorator_arguments["eq"]
  258. and info.get("__eq__") is None
  259. or decorator_arguments["order"]
  260. ):
  261. # Type variable for self types in generated methods.
  262. obj_type = self._api.named_type("builtins.object")
  263. self_tvar_expr = TypeVarExpr(
  264. SELF_TVAR_NAME,
  265. info.fullname + "." + SELF_TVAR_NAME,
  266. [],
  267. obj_type,
  268. AnyType(TypeOfAny.from_omitted_generics),
  269. )
  270. info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr)
  271. # Add <, >, <=, >=, but only if the class has an eq method.
  272. if decorator_arguments["order"]:
  273. if not decorator_arguments["eq"]:
  274. self._api.fail('"eq" must be True if "order" is True', self._reason)
  275. for method_name in ["__lt__", "__gt__", "__le__", "__ge__"]:
  276. # Like for __eq__ and __ne__, we want "other" to match
  277. # the self type.
  278. obj_type = self._api.named_type("builtins.object")
  279. order_tvar_def = TypeVarType(
  280. SELF_TVAR_NAME,
  281. info.fullname + "." + SELF_TVAR_NAME,
  282. id=-1,
  283. values=[],
  284. upper_bound=obj_type,
  285. default=AnyType(TypeOfAny.from_omitted_generics),
  286. )
  287. order_return_type = self._api.named_type("builtins.bool")
  288. order_args = [
  289. Argument(Var("other", order_tvar_def), order_tvar_def, None, ARG_POS)
  290. ]
  291. existing_method = info.get(method_name)
  292. if existing_method is not None and not existing_method.plugin_generated:
  293. assert existing_method.node
  294. self._api.fail(
  295. f'You may not have a custom "{method_name}" method when "order" is True',
  296. existing_method.node,
  297. )
  298. add_method_to_class(
  299. self._api,
  300. self._cls,
  301. method_name,
  302. args=order_args,
  303. return_type=order_return_type,
  304. self_type=order_tvar_def,
  305. tvar_def=order_tvar_def,
  306. )
  307. parent_decorator_arguments = []
  308. for parent in info.mro[1:-1]:
  309. parent_args = parent.metadata.get("dataclass")
  310. # Ignore parent classes that directly specify a dataclass transform-decorated metaclass
  311. # when searching for usage of the frozen parameter. PEP 681 states that a class that
  312. # directly specifies such a metaclass must be treated as neither frozen nor non-frozen.
  313. if parent_args and not _has_direct_dataclass_transform_metaclass(parent):
  314. parent_decorator_arguments.append(parent_args)
  315. if decorator_arguments["frozen"]:
  316. if any(not parent["frozen"] for parent in parent_decorator_arguments):
  317. self._api.fail("Cannot inherit frozen dataclass from a non-frozen one", info)
  318. self._propertize_callables(attributes, settable=False)
  319. self._freeze(attributes)
  320. else:
  321. if any(parent["frozen"] for parent in parent_decorator_arguments):
  322. self._api.fail("Cannot inherit non-frozen dataclass from a frozen one", info)
  323. self._propertize_callables(attributes)
  324. if decorator_arguments["slots"]:
  325. self.add_slots(info, attributes, correct_version=py_version >= (3, 10))
  326. self.reset_init_only_vars(info, attributes)
  327. if (
  328. decorator_arguments["match_args"]
  329. and (
  330. "__match_args__" not in info.names or info.names["__match_args__"].plugin_generated
  331. )
  332. and attributes
  333. and py_version >= (3, 10)
  334. ):
  335. str_type = self._api.named_type("builtins.str")
  336. literals: list[Type] = [
  337. LiteralType(attr.name, str_type) for attr in attributes if attr.is_in_init
  338. ]
  339. match_args_type = TupleType(literals, self._api.named_type("builtins.tuple"))
  340. add_attribute_to_class(self._api, self._cls, "__match_args__", match_args_type)
  341. self._add_dataclass_fields_magic_attribute()
  342. if self._spec is _TRANSFORM_SPEC_FOR_DATACLASSES:
  343. self._add_internal_replace_method(attributes)
  344. if "__post_init__" in info.names:
  345. self._add_internal_post_init_method(attributes)
  346. info.metadata["dataclass"] = {
  347. "attributes": [attr.serialize() for attr in attributes],
  348. "frozen": decorator_arguments["frozen"],
  349. }
  350. return True
  351. def _add_internal_replace_method(self, attributes: list[DataclassAttribute]) -> None:
  352. """
  353. Stashes the signature of 'dataclasses.replace(...)' for this specific dataclass
  354. to be used later whenever 'dataclasses.replace' is called for this dataclass.
  355. """
  356. add_method_to_class(
  357. self._api,
  358. self._cls,
  359. _INTERNAL_REPLACE_SYM_NAME,
  360. args=[attr.to_argument(self._cls.info, of="replace") for attr in attributes],
  361. return_type=NoneType(),
  362. is_staticmethod=True,
  363. )
  364. def _add_internal_post_init_method(self, attributes: list[DataclassAttribute]) -> None:
  365. add_method_to_class(
  366. self._api,
  367. self._cls,
  368. _INTERNAL_POST_INIT_SYM_NAME,
  369. args=[
  370. attr.to_argument(self._cls.info, of="__post_init__")
  371. for attr in attributes
  372. if attr.is_init_var
  373. ],
  374. return_type=NoneType(),
  375. )
  376. def add_slots(
  377. self, info: TypeInfo, attributes: list[DataclassAttribute], *, correct_version: bool
  378. ) -> None:
  379. if not correct_version:
  380. # This means that version is lower than `3.10`,
  381. # it is just a non-existent argument for `dataclass` function.
  382. self._api.fail(
  383. 'Keyword argument "slots" for "dataclass" '
  384. "is only valid in Python 3.10 and higher",
  385. self._reason,
  386. )
  387. return
  388. generated_slots = {attr.name for attr in attributes}
  389. if (info.slots is not None and info.slots != generated_slots) or info.names.get(
  390. "__slots__"
  391. ):
  392. # This means we have a slots conflict.
  393. # Class explicitly specifies a different `__slots__` field.
  394. # And `@dataclass(slots=True)` is used.
  395. # In runtime this raises a type error.
  396. self._api.fail(
  397. '"{}" both defines "__slots__" and is used with "slots=True"'.format(
  398. self._cls.name
  399. ),
  400. self._cls,
  401. )
  402. return
  403. info.slots = generated_slots
  404. # Now, insert `.__slots__` attribute to class namespace:
  405. slots_type = TupleType(
  406. [self._api.named_type("builtins.str") for _ in generated_slots],
  407. self._api.named_type("builtins.tuple"),
  408. )
  409. add_attribute_to_class(self._api, self._cls, "__slots__", slots_type)
  410. def reset_init_only_vars(self, info: TypeInfo, attributes: list[DataclassAttribute]) -> None:
  411. """Remove init-only vars from the class and reset init var declarations."""
  412. for attr in attributes:
  413. if attr.is_init_var:
  414. if attr.name in info.names:
  415. del info.names[attr.name]
  416. else:
  417. # Nodes of superclass InitVars not used in __init__ cannot be reached.
  418. assert attr.is_init_var
  419. for stmt in info.defn.defs.body:
  420. if isinstance(stmt, AssignmentStmt) and stmt.unanalyzed_type:
  421. lvalue = stmt.lvalues[0]
  422. if isinstance(lvalue, NameExpr) and lvalue.name == attr.name:
  423. # Reset node so that another semantic analysis pass will
  424. # recreate a symbol node for this attribute.
  425. lvalue.node = None
  426. def _get_assignment_statements_from_if_statement(
  427. self, stmt: IfStmt
  428. ) -> Iterator[AssignmentStmt]:
  429. for body in stmt.body:
  430. if not body.is_unreachable:
  431. yield from self._get_assignment_statements_from_block(body)
  432. if stmt.else_body is not None and not stmt.else_body.is_unreachable:
  433. yield from self._get_assignment_statements_from_block(stmt.else_body)
  434. def _get_assignment_statements_from_block(self, block: Block) -> Iterator[AssignmentStmt]:
  435. for stmt in block.body:
  436. if isinstance(stmt, AssignmentStmt):
  437. yield stmt
  438. elif isinstance(stmt, IfStmt):
  439. yield from self._get_assignment_statements_from_if_statement(stmt)
  440. def collect_attributes(self) -> list[DataclassAttribute] | None:
  441. """Collect all attributes declared in the dataclass and its parents.
  442. All assignments of the form
  443. a: SomeType
  444. b: SomeOtherType = ...
  445. are collected.
  446. Return None if some dataclass base class hasn't been processed
  447. yet and thus we'll need to ask for another pass.
  448. """
  449. cls = self._cls
  450. # First, collect attributes belonging to any class in the MRO, ignoring duplicates.
  451. #
  452. # We iterate through the MRO in reverse because attrs defined in the parent must appear
  453. # earlier in the attributes list than attrs defined in the child. See:
  454. # https://docs.python.org/3/library/dataclasses.html#inheritance
  455. #
  456. # However, we also want attributes defined in the subtype to override ones defined
  457. # in the parent. We can implement this via a dict without disrupting the attr order
  458. # because dicts preserve insertion order in Python 3.7+.
  459. found_attrs: dict[str, DataclassAttribute] = {}
  460. found_dataclass_supertype = False
  461. for info in reversed(cls.info.mro[1:-1]):
  462. if "dataclass_tag" in info.metadata and "dataclass" not in info.metadata:
  463. # We haven't processed the base class yet. Need another pass.
  464. return None
  465. if "dataclass" not in info.metadata:
  466. continue
  467. # Each class depends on the set of attributes in its dataclass ancestors.
  468. self._api.add_plugin_dependency(make_wildcard_trigger(info.fullname))
  469. found_dataclass_supertype = True
  470. for data in info.metadata["dataclass"]["attributes"]:
  471. name: str = data["name"]
  472. attr = DataclassAttribute.deserialize(info, data, self._api)
  473. # TODO: We shouldn't be performing type operations during the main
  474. # semantic analysis pass, since some TypeInfo attributes might
  475. # still be in flux. This should be performed in a later phase.
  476. attr.expand_typevar_from_subtype(cls.info)
  477. found_attrs[name] = attr
  478. sym_node = cls.info.names.get(name)
  479. if sym_node and sym_node.node and not isinstance(sym_node.node, Var):
  480. self._api.fail(
  481. "Dataclass attribute may only be overridden by another attribute",
  482. sym_node.node,
  483. )
  484. # Second, collect attributes belonging to the current class.
  485. current_attr_names: set[str] = set()
  486. kw_only = self._get_bool_arg("kw_only", self._spec.kw_only_default)
  487. for stmt in self._get_assignment_statements_from_block(cls.defs):
  488. # Any assignment that doesn't use the new type declaration
  489. # syntax can be ignored out of hand.
  490. if not stmt.new_syntax:
  491. continue
  492. # a: int, b: str = 1, 'foo' is not supported syntax so we
  493. # don't have to worry about it.
  494. lhs = stmt.lvalues[0]
  495. if not isinstance(lhs, NameExpr):
  496. continue
  497. sym = cls.info.names.get(lhs.name)
  498. if sym is None:
  499. # There was probably a semantic analysis error.
  500. continue
  501. node = sym.node
  502. assert not isinstance(node, PlaceholderNode)
  503. if isinstance(node, TypeAlias):
  504. self._api.fail(
  505. ("Type aliases inside dataclass definitions are not supported at runtime"),
  506. node,
  507. )
  508. # Skip processing this node. This doesn't match the runtime behaviour,
  509. # but the only alternative would be to modify the SymbolTable,
  510. # and it's a little hairy to do that in a plugin.
  511. continue
  512. assert isinstance(node, Var)
  513. # x: ClassVar[int] is ignored by dataclasses.
  514. if node.is_classvar:
  515. continue
  516. # x: InitVar[int] is turned into x: int and is removed from the class.
  517. is_init_var = False
  518. node_type = get_proper_type(node.type)
  519. if (
  520. isinstance(node_type, Instance)
  521. and node_type.type.fullname == "dataclasses.InitVar"
  522. ):
  523. is_init_var = True
  524. node.type = node_type.args[0]
  525. if self._is_kw_only_type(node_type):
  526. kw_only = True
  527. has_field_call, field_args = self._collect_field_args(stmt.rvalue)
  528. is_in_init_param = field_args.get("init")
  529. if is_in_init_param is None:
  530. is_in_init = self._get_default_init_value_for_field_specifier(stmt.rvalue)
  531. else:
  532. is_in_init = bool(self._api.parse_bool(is_in_init_param))
  533. has_default = False
  534. # Ensure that something like x: int = field() is rejected
  535. # after an attribute with a default.
  536. if has_field_call:
  537. has_default = (
  538. "default" in field_args
  539. or "default_factory" in field_args
  540. # alias for default_factory defined in PEP 681
  541. or "factory" in field_args
  542. )
  543. # All other assignments are already type checked.
  544. elif not isinstance(stmt.rvalue, TempNode):
  545. has_default = True
  546. if not has_default and self._spec is _TRANSFORM_SPEC_FOR_DATACLASSES:
  547. # Make all non-default dataclass attributes implicit because they are de-facto
  548. # set on self in the generated __init__(), not in the class body. On the other
  549. # hand, we don't know how custom dataclass transforms initialize attributes,
  550. # so we don't treat them as implicit. This is required to support descriptors
  551. # (https://github.com/python/mypy/issues/14868).
  552. sym.implicit = True
  553. is_kw_only = kw_only
  554. # Use the kw_only field arg if it is provided. Otherwise use the
  555. # kw_only value from the decorator parameter.
  556. field_kw_only_param = field_args.get("kw_only")
  557. if field_kw_only_param is not None:
  558. value = self._api.parse_bool(field_kw_only_param)
  559. if value is not None:
  560. is_kw_only = value
  561. else:
  562. self._api.fail('"kw_only" argument must be a boolean literal', stmt.rvalue)
  563. if sym.type is None and node.is_final and node.is_inferred:
  564. # This is a special case, assignment like x: Final = 42 is classified
  565. # annotated above, but mypy strips the `Final` turning it into x = 42.
  566. # We do not support inferred types in dataclasses, so we can try inferring
  567. # type for simple literals, and otherwise require an explicit type
  568. # argument for Final[...].
  569. typ = self._api.analyze_simple_literal_type(stmt.rvalue, is_final=True)
  570. if typ:
  571. node.type = typ
  572. else:
  573. self._api.fail(
  574. "Need type argument for Final[...] with non-literal default in dataclass",
  575. stmt,
  576. )
  577. node.type = AnyType(TypeOfAny.from_error)
  578. alias = None
  579. if "alias" in field_args:
  580. alias = self._api.parse_str_literal(field_args["alias"])
  581. if alias is None:
  582. self._api.fail(
  583. message_registry.DATACLASS_FIELD_ALIAS_MUST_BE_LITERAL,
  584. stmt.rvalue,
  585. code=errorcodes.LITERAL_REQ,
  586. )
  587. current_attr_names.add(lhs.name)
  588. with state.strict_optional_set(self._api.options.strict_optional):
  589. init_type = self._infer_dataclass_attr_init_type(sym, lhs.name, stmt)
  590. found_attrs[lhs.name] = DataclassAttribute(
  591. name=lhs.name,
  592. alias=alias,
  593. is_in_init=is_in_init,
  594. is_init_var=is_init_var,
  595. has_default=has_default,
  596. line=stmt.line,
  597. column=stmt.column,
  598. type=init_type,
  599. info=cls.info,
  600. kw_only=is_kw_only,
  601. is_neither_frozen_nor_nonfrozen=_has_direct_dataclass_transform_metaclass(
  602. cls.info
  603. ),
  604. api=self._api,
  605. )
  606. all_attrs = list(found_attrs.values())
  607. if found_dataclass_supertype:
  608. all_attrs.sort(key=lambda a: a.kw_only)
  609. # Third, ensure that arguments without a default don't follow
  610. # arguments that have a default and that the KW_ONLY sentinel
  611. # is only provided once.
  612. found_default = False
  613. found_kw_sentinel = False
  614. for attr in all_attrs:
  615. # If we find any attribute that is_in_init, not kw_only, and that
  616. # doesn't have a default after one that does have one,
  617. # then that's an error.
  618. if found_default and attr.is_in_init and not attr.has_default and not attr.kw_only:
  619. # If the issue comes from merging different classes, report it
  620. # at the class definition point.
  621. context: Context = cls
  622. if attr.name in current_attr_names:
  623. context = Context(line=attr.line, column=attr.column)
  624. self._api.fail(
  625. "Attributes without a default cannot follow attributes with one", context
  626. )
  627. found_default = found_default or (attr.has_default and attr.is_in_init)
  628. if found_kw_sentinel and self._is_kw_only_type(attr.type):
  629. context = cls
  630. if attr.name in current_attr_names:
  631. context = Context(line=attr.line, column=attr.column)
  632. self._api.fail(
  633. "There may not be more than one field with the KW_ONLY type", context
  634. )
  635. found_kw_sentinel = found_kw_sentinel or self._is_kw_only_type(attr.type)
  636. return all_attrs
  637. def _freeze(self, attributes: list[DataclassAttribute]) -> None:
  638. """Converts all attributes to @property methods in order to
  639. emulate frozen classes.
  640. """
  641. info = self._cls.info
  642. for attr in attributes:
  643. # Classes that directly specify a dataclass_transform metaclass must be neither frozen
  644. # non non-frozen per PEP681. Though it is surprising, this means that attributes from
  645. # such a class must be writable even if the rest of the class heirarchy is frozen. This
  646. # matches the behavior of Pyright (the reference implementation).
  647. if attr.is_neither_frozen_nor_nonfrozen:
  648. continue
  649. sym_node = info.names.get(attr.name)
  650. if sym_node is not None:
  651. var = sym_node.node
  652. if isinstance(var, Var):
  653. var.is_property = True
  654. else:
  655. var = attr.to_var(info)
  656. var.info = info
  657. var.is_property = True
  658. var._fullname = info.fullname + "." + var.name
  659. info.names[var.name] = SymbolTableNode(MDEF, var)
  660. def _propertize_callables(
  661. self, attributes: list[DataclassAttribute], settable: bool = True
  662. ) -> None:
  663. """Converts all attributes with callable types to @property methods.
  664. This avoids the typechecker getting confused and thinking that
  665. `my_dataclass_instance.callable_attr(foo)` is going to receive a
  666. `self` argument (it is not).
  667. """
  668. info = self._cls.info
  669. for attr in attributes:
  670. if isinstance(get_proper_type(attr.type), CallableType):
  671. var = attr.to_var(info)
  672. var.info = info
  673. var.is_property = True
  674. var.is_settable_property = settable
  675. var._fullname = info.fullname + "." + var.name
  676. info.names[var.name] = SymbolTableNode(MDEF, var)
  677. def _is_kw_only_type(self, node: Type | None) -> bool:
  678. """Checks if the type of the node is the KW_ONLY sentinel value."""
  679. if node is None:
  680. return False
  681. node_type = get_proper_type(node)
  682. if not isinstance(node_type, Instance):
  683. return False
  684. return node_type.type.fullname == "dataclasses.KW_ONLY"
  685. def _add_dataclass_fields_magic_attribute(self) -> None:
  686. attr_name = "__dataclass_fields__"
  687. any_type = AnyType(TypeOfAny.explicit)
  688. # For `dataclasses`, use the type `dict[str, Field[Any]]` for accuracy. For dataclass
  689. # transforms, it's inaccurate to use `Field` since a given transform may use a completely
  690. # different type (or none); fall back to `Any` there.
  691. #
  692. # In either case, we're aiming to match the Typeshed stub for `is_dataclass`, which expects
  693. # the instance to have a `__dataclass_fields__` attribute of type `dict[str, Field[Any]]`.
  694. if self._spec is _TRANSFORM_SPEC_FOR_DATACLASSES:
  695. field_type = self._api.named_type_or_none("dataclasses.Field", [any_type]) or any_type
  696. else:
  697. field_type = any_type
  698. attr_type = self._api.named_type(
  699. "builtins.dict", [self._api.named_type("builtins.str"), field_type]
  700. )
  701. var = Var(name=attr_name, type=attr_type)
  702. var.info = self._cls.info
  703. var._fullname = self._cls.info.fullname + "." + attr_name
  704. var.is_classvar = True
  705. self._cls.info.names[attr_name] = SymbolTableNode(
  706. kind=MDEF, node=var, plugin_generated=True
  707. )
  708. def _collect_field_args(self, expr: Expression) -> tuple[bool, dict[str, Expression]]:
  709. """Returns a tuple where the first value represents whether or not
  710. the expression is a call to dataclass.field and the second is a
  711. dictionary of the keyword arguments that field() was called with.
  712. """
  713. if (
  714. isinstance(expr, CallExpr)
  715. and isinstance(expr.callee, RefExpr)
  716. and expr.callee.fullname in self._spec.field_specifiers
  717. ):
  718. # field() only takes keyword arguments.
  719. args = {}
  720. for name, arg, kind in zip(expr.arg_names, expr.args, expr.arg_kinds):
  721. if not kind.is_named():
  722. if kind.is_named(star=True):
  723. # This means that `field` is used with `**` unpacking,
  724. # the best we can do for now is not to fail.
  725. # TODO: we can infer what's inside `**` and try to collect it.
  726. message = 'Unpacking **kwargs in "field()" is not supported'
  727. elif self._spec is not _TRANSFORM_SPEC_FOR_DATACLASSES:
  728. # dataclasses.field can only be used with keyword args, but this
  729. # restriction is only enforced for the *standardized* arguments to
  730. # dataclass_transform field specifiers. If this is not a
  731. # dataclasses.dataclass class, we can just skip positional args safely.
  732. continue
  733. else:
  734. message = '"field()" does not accept positional arguments'
  735. self._api.fail(message, expr)
  736. return True, {}
  737. assert name is not None
  738. args[name] = arg
  739. return True, args
  740. return False, {}
  741. def _get_bool_arg(self, name: str, default: bool) -> bool:
  742. # Expressions are always CallExprs (either directly or via a wrapper like Decorator), so
  743. # we can use the helpers from common
  744. if isinstance(self._reason, Expression):
  745. return _get_decorator_bool_argument(
  746. ClassDefContext(self._cls, self._reason, self._api), name, default
  747. )
  748. # Subclass/metaclass use of `typing.dataclass_transform` reads the parameters from the
  749. # class's keyword arguments (ie `class Subclass(Parent, kwarg1=..., kwarg2=...)`)
  750. expression = self._cls.keywords.get(name)
  751. if expression is not None:
  752. return require_bool_literal_argument(self._api, expression, name, default)
  753. return default
  754. def _get_default_init_value_for_field_specifier(self, call: Expression) -> bool:
  755. """
  756. Find a default value for the `init` parameter of the specifier being called. If the
  757. specifier's type signature includes an `init` parameter with a type of `Literal[True]` or
  758. `Literal[False]`, return the appropriate boolean value from the literal. Otherwise,
  759. fall back to the standard default of `True`.
  760. """
  761. if not isinstance(call, CallExpr):
  762. return True
  763. specifier_type = _get_callee_type(call)
  764. if specifier_type is None:
  765. return True
  766. parameter = specifier_type.argument_by_name("init")
  767. if parameter is None:
  768. return True
  769. literals = try_getting_literals_from_type(parameter.typ, bool, "builtins.bool")
  770. if literals is None or len(literals) != 1:
  771. return True
  772. return literals[0]
  773. def _infer_dataclass_attr_init_type(
  774. self, sym: SymbolTableNode, name: str, context: Context
  775. ) -> Type | None:
  776. """Infer __init__ argument type for an attribute.
  777. In particular, possibly use the signature of __set__.
  778. """
  779. default = sym.type
  780. if sym.implicit:
  781. return default
  782. t = get_proper_type(sym.type)
  783. # Perform a simple-minded inference from the signature of __set__, if present.
  784. # We can't use mypy.checkmember here, since this plugin runs before type checking.
  785. # We only support some basic scanerios here, which is hopefully sufficient for
  786. # the vast majority of use cases.
  787. if not isinstance(t, Instance):
  788. return default
  789. setter = t.type.get("__set__")
  790. if setter:
  791. if isinstance(setter.node, FuncDef):
  792. super_info = t.type.get_containing_type_info("__set__")
  793. assert super_info
  794. if setter.type:
  795. setter_type = get_proper_type(
  796. map_type_from_supertype(setter.type, t.type, super_info)
  797. )
  798. else:
  799. return AnyType(TypeOfAny.unannotated)
  800. if isinstance(setter_type, CallableType) and setter_type.arg_kinds == [
  801. ARG_POS,
  802. ARG_POS,
  803. ARG_POS,
  804. ]:
  805. return expand_type_by_instance(setter_type.arg_types[2], t)
  806. else:
  807. self._api.fail(
  808. f'Unsupported signature for "__set__" in "{t.type.name}"', context
  809. )
  810. else:
  811. self._api.fail(f'Unsupported "__set__" in "{t.type.name}"', context)
  812. return default
  813. def add_dataclass_tag(info: TypeInfo) -> None:
  814. # The value is ignored, only the existence matters.
  815. info.metadata["dataclass_tag"] = {}
  816. def dataclass_tag_callback(ctx: ClassDefContext) -> None:
  817. """Record that we have a dataclass in the main semantic analysis pass.
  818. The later pass implemented by DataclassTransformer will use this
  819. to detect dataclasses in base classes.
  820. """
  821. add_dataclass_tag(ctx.cls.info)
  822. def dataclass_class_maker_callback(ctx: ClassDefContext) -> bool:
  823. """Hooks into the class typechecking process to add support for dataclasses."""
  824. transformer = DataclassTransformer(
  825. ctx.cls, ctx.reason, _get_transform_spec(ctx.reason), ctx.api
  826. )
  827. return transformer.transform()
  828. def _get_transform_spec(reason: Expression) -> DataclassTransformSpec:
  829. """Find the relevant transform parameters from the decorator/parent class/metaclass that
  830. triggered the dataclasses plugin.
  831. Although the resulting DataclassTransformSpec is based on the typing.dataclass_transform
  832. function, we also use it for traditional dataclasses.dataclass classes as well for simplicity.
  833. In those cases, we return a default spec rather than one based on a call to
  834. `typing.dataclass_transform`.
  835. """
  836. if _is_dataclasses_decorator(reason):
  837. return _TRANSFORM_SPEC_FOR_DATACLASSES
  838. spec = find_dataclass_transform_spec(reason)
  839. assert spec is not None, (
  840. "trying to find dataclass transform spec, but reason is neither dataclasses.dataclass nor "
  841. "decorated with typing.dataclass_transform"
  842. )
  843. return spec
  844. def _is_dataclasses_decorator(node: Node) -> bool:
  845. if isinstance(node, CallExpr):
  846. node = node.callee
  847. if isinstance(node, RefExpr):
  848. return node.fullname in dataclass_makers
  849. return False
  850. def _has_direct_dataclass_transform_metaclass(info: TypeInfo) -> bool:
  851. return (
  852. info.declared_metaclass is not None
  853. and info.declared_metaclass.type.dataclass_transform_spec is not None
  854. )
  855. def _fail_not_dataclass(ctx: FunctionSigContext, t: Type, parent_t: Type) -> None:
  856. t_name = format_type_bare(t, ctx.api.options)
  857. if parent_t is t:
  858. msg = (
  859. f'Argument 1 to "replace" has a variable type "{t_name}" not bound to a dataclass'
  860. if isinstance(t, TypeVarType)
  861. else f'Argument 1 to "replace" has incompatible type "{t_name}"; expected a dataclass'
  862. )
  863. else:
  864. pt_name = format_type_bare(parent_t, ctx.api.options)
  865. msg = (
  866. f'Argument 1 to "replace" has type "{pt_name}" whose item "{t_name}" is not bound to a dataclass'
  867. if isinstance(t, TypeVarType)
  868. else f'Argument 1 to "replace" has incompatible type "{pt_name}" whose item "{t_name}" is not a dataclass'
  869. )
  870. ctx.api.fail(msg, ctx.context)
  871. def _get_expanded_dataclasses_fields(
  872. ctx: FunctionSigContext, typ: ProperType, display_typ: ProperType, parent_typ: ProperType
  873. ) -> list[CallableType] | None:
  874. """
  875. For a given type, determine what dataclasses it can be: for each class, return the field types.
  876. For generic classes, the field types are expanded.
  877. If the type contains Any or a non-dataclass, returns None; in the latter case, also reports an error.
  878. """
  879. if isinstance(typ, AnyType):
  880. return None
  881. elif isinstance(typ, UnionType):
  882. ret: list[CallableType] | None = []
  883. for item in typ.relevant_items():
  884. item = get_proper_type(item)
  885. item_types = _get_expanded_dataclasses_fields(ctx, item, item, parent_typ)
  886. if ret is not None and item_types is not None:
  887. ret += item_types
  888. else:
  889. ret = None # but keep iterating to emit all errors
  890. return ret
  891. elif isinstance(typ, TypeVarType):
  892. return _get_expanded_dataclasses_fields(
  893. ctx, get_proper_type(typ.upper_bound), display_typ, parent_typ
  894. )
  895. elif isinstance(typ, Instance):
  896. replace_sym = typ.type.get_method(_INTERNAL_REPLACE_SYM_NAME)
  897. if replace_sym is None:
  898. _fail_not_dataclass(ctx, display_typ, parent_typ)
  899. return None
  900. replace_sig = replace_sym.type
  901. assert isinstance(replace_sig, ProperType)
  902. assert isinstance(replace_sig, CallableType)
  903. return [expand_type_by_instance(replace_sig, typ)]
  904. else:
  905. _fail_not_dataclass(ctx, display_typ, parent_typ)
  906. return None
  907. # TODO: we can potentially get the function signature hook to allow returning a union
  908. # and leave this to the regular machinery of resolving a union of callables
  909. # (https://github.com/python/mypy/issues/15457)
  910. def _meet_replace_sigs(sigs: list[CallableType]) -> CallableType:
  911. """
  912. Produces the lowest bound of the 'replace' signatures of multiple dataclasses.
  913. """
  914. args = {
  915. name: (typ, kind)
  916. for name, typ, kind in zip(sigs[0].arg_names, sigs[0].arg_types, sigs[0].arg_kinds)
  917. }
  918. for sig in sigs[1:]:
  919. sig_args = {
  920. name: (typ, kind)
  921. for name, typ, kind in zip(sig.arg_names, sig.arg_types, sig.arg_kinds)
  922. }
  923. for name in (*args.keys(), *sig_args.keys()):
  924. sig_typ, sig_kind = args.get(name, (UninhabitedType(), ARG_NAMED_OPT))
  925. sig2_typ, sig2_kind = sig_args.get(name, (UninhabitedType(), ARG_NAMED_OPT))
  926. args[name] = (
  927. meet_types(sig_typ, sig2_typ),
  928. ARG_NAMED_OPT if sig_kind == sig2_kind == ARG_NAMED_OPT else ARG_NAMED,
  929. )
  930. return sigs[0].copy_modified(
  931. arg_names=list(args.keys()),
  932. arg_types=[typ for typ, _ in args.values()],
  933. arg_kinds=[kind for _, kind in args.values()],
  934. )
  935. def replace_function_sig_callback(ctx: FunctionSigContext) -> CallableType:
  936. """
  937. Returns a signature for the 'dataclasses.replace' function that's dependent on the type
  938. of the first positional argument.
  939. """
  940. if len(ctx.args) != 2:
  941. # Ideally the name and context should be callee's, but we don't have it in FunctionSigContext.
  942. ctx.api.fail(f'"{ctx.default_signature.name}" has unexpected type annotation', ctx.context)
  943. return ctx.default_signature
  944. if len(ctx.args[0]) != 1:
  945. return ctx.default_signature # leave it to the type checker to complain
  946. obj_arg = ctx.args[0][0]
  947. obj_type = get_proper_type(ctx.api.get_expression_type(obj_arg))
  948. inst_type_str = format_type_bare(obj_type, ctx.api.options)
  949. replace_sigs = _get_expanded_dataclasses_fields(ctx, obj_type, obj_type, obj_type)
  950. if replace_sigs is None:
  951. return ctx.default_signature
  952. replace_sig = _meet_replace_sigs(replace_sigs)
  953. return replace_sig.copy_modified(
  954. arg_names=[None, *replace_sig.arg_names],
  955. arg_kinds=[ARG_POS, *replace_sig.arg_kinds],
  956. arg_types=[obj_type, *replace_sig.arg_types],
  957. ret_type=obj_type,
  958. fallback=ctx.default_signature.fallback,
  959. name=f"{ctx.default_signature.name} of {inst_type_str}",
  960. )
  961. def is_processed_dataclass(info: TypeInfo | None) -> bool:
  962. return info is not None and "dataclass" in info.metadata
  963. def check_post_init(api: TypeChecker, defn: FuncItem, info: TypeInfo) -> None:
  964. if defn.type is None:
  965. return
  966. assert isinstance(defn.type, FunctionLike)
  967. ideal_sig_method = info.get_method(_INTERNAL_POST_INIT_SYM_NAME)
  968. assert ideal_sig_method is not None and ideal_sig_method.type is not None
  969. ideal_sig = ideal_sig_method.type
  970. assert isinstance(ideal_sig, ProperType) # we set it ourselves
  971. assert isinstance(ideal_sig, CallableType)
  972. ideal_sig = ideal_sig.copy_modified(name="__post_init__")
  973. api.check_override(
  974. override=defn.type,
  975. original=ideal_sig,
  976. name="__post_init__",
  977. name_in_super="__post_init__",
  978. supertype="dataclass",
  979. original_class_or_static=False,
  980. override_class_or_static=False,
  981. node=defn,
  982. )