dataclasses.py 36 KB

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