mypy.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190
  1. """This module includes classes and functions designed specifically for use with the mypy plugin."""
  2. from __future__ import annotations
  3. import sys
  4. from configparser import ConfigParser
  5. from typing import Any, Callable, Iterator
  6. from mypy.errorcodes import ErrorCode
  7. from mypy.expandtype import expand_type, expand_type_by_instance
  8. from mypy.nodes import (
  9. ARG_NAMED,
  10. ARG_NAMED_OPT,
  11. ARG_OPT,
  12. ARG_POS,
  13. ARG_STAR2,
  14. MDEF,
  15. Argument,
  16. AssignmentStmt,
  17. Block,
  18. CallExpr,
  19. ClassDef,
  20. Context,
  21. Decorator,
  22. DictExpr,
  23. EllipsisExpr,
  24. Expression,
  25. FuncDef,
  26. IfStmt,
  27. JsonDict,
  28. MemberExpr,
  29. NameExpr,
  30. PassStmt,
  31. PlaceholderNode,
  32. RefExpr,
  33. Statement,
  34. StrExpr,
  35. SymbolTableNode,
  36. TempNode,
  37. TypeAlias,
  38. TypeInfo,
  39. Var,
  40. )
  41. from mypy.options import Options
  42. from mypy.plugin import (
  43. CheckerPluginInterface,
  44. ClassDefContext,
  45. FunctionContext,
  46. MethodContext,
  47. Plugin,
  48. ReportConfigContext,
  49. SemanticAnalyzerPluginInterface,
  50. )
  51. from mypy.plugins import dataclasses
  52. from mypy.plugins.common import (
  53. deserialize_and_fixup_type,
  54. )
  55. from mypy.semanal import set_callable_name
  56. from mypy.server.trigger import make_wildcard_trigger
  57. from mypy.state import state
  58. from mypy.typeops import map_type_from_supertype
  59. from mypy.types import (
  60. AnyType,
  61. CallableType,
  62. Instance,
  63. NoneType,
  64. Overloaded,
  65. Type,
  66. TypeOfAny,
  67. TypeType,
  68. TypeVarType,
  69. UnionType,
  70. get_proper_type,
  71. )
  72. from mypy.typevars import fill_typevars
  73. from mypy.util import get_unique_redefinition_name
  74. from mypy.version import __version__ as mypy_version
  75. from pydantic._internal import _fields
  76. from pydantic.version import parse_mypy_version
  77. try:
  78. from mypy.types import TypeVarDef # type: ignore[attr-defined]
  79. except ImportError: # pragma: no cover
  80. # Backward-compatible with TypeVarDef from Mypy 0.930.
  81. from mypy.types import TypeVarType as TypeVarDef
  82. CONFIGFILE_KEY = 'pydantic-mypy'
  83. METADATA_KEY = 'pydantic-mypy-metadata'
  84. BASEMODEL_FULLNAME = 'pydantic.main.BaseModel'
  85. BASESETTINGS_FULLNAME = 'pydantic_settings.main.BaseSettings'
  86. MODEL_METACLASS_FULLNAME = 'pydantic._internal._model_construction.ModelMetaclass'
  87. FIELD_FULLNAME = 'pydantic.fields.Field'
  88. DATACLASS_FULLNAME = 'pydantic.dataclasses.dataclass'
  89. MODEL_VALIDATOR_FULLNAME = 'pydantic.functional_validators.model_validator'
  90. DECORATOR_FULLNAMES = {
  91. 'pydantic.functional_validators.field_validator',
  92. 'pydantic.functional_validators.model_validator',
  93. 'pydantic.functional_serializers.serializer',
  94. 'pydantic.functional_serializers.model_serializer',
  95. 'pydantic.deprecated.class_validators.validator',
  96. 'pydantic.deprecated.class_validators.root_validator',
  97. }
  98. MYPY_VERSION_TUPLE = parse_mypy_version(mypy_version)
  99. BUILTINS_NAME = 'builtins' if MYPY_VERSION_TUPLE >= (0, 930) else '__builtins__'
  100. # Increment version if plugin changes and mypy caches should be invalidated
  101. __version__ = 2
  102. def plugin(version: str) -> type[Plugin]:
  103. """`version` is the mypy version string.
  104. We might want to use this to print a warning if the mypy version being used is
  105. newer, or especially older, than we expect (or need).
  106. Args:
  107. version: The mypy version string.
  108. Return:
  109. The Pydantic mypy plugin type.
  110. """
  111. return PydanticPlugin
  112. class PydanticPlugin(Plugin):
  113. """The Pydantic mypy plugin."""
  114. def __init__(self, options: Options) -> None:
  115. self.plugin_config = PydanticPluginConfig(options)
  116. self._plugin_data = self.plugin_config.to_data()
  117. super().__init__(options)
  118. def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], bool] | None:
  119. """Update Pydantic model class."""
  120. sym = self.lookup_fully_qualified(fullname)
  121. if sym and isinstance(sym.node, TypeInfo): # pragma: no branch
  122. # No branching may occur if the mypy cache has not been cleared
  123. if any(base.fullname == BASEMODEL_FULLNAME for base in sym.node.mro):
  124. return self._pydantic_model_class_maker_callback
  125. return None
  126. def get_metaclass_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:
  127. """Update Pydantic `ModelMetaclass` definition."""
  128. if fullname == MODEL_METACLASS_FULLNAME:
  129. return self._pydantic_model_metaclass_marker_callback
  130. return None
  131. def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:
  132. """Adjust the return type of the `Field` function."""
  133. sym = self.lookup_fully_qualified(fullname)
  134. if sym and sym.fullname == FIELD_FULLNAME:
  135. return self._pydantic_field_callback
  136. return None
  137. def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:
  138. """Adjust return type of `from_orm` method call."""
  139. if fullname.endswith('.from_orm'):
  140. return from_attributes_callback
  141. return None
  142. def get_class_decorator_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:
  143. """Mark pydantic.dataclasses as dataclass.
  144. Mypy version 1.1.1 added support for `@dataclass_transform` decorator.
  145. """
  146. if fullname == DATACLASS_FULLNAME and MYPY_VERSION_TUPLE < (1, 1):
  147. return dataclasses.dataclass_class_maker_callback # type: ignore[return-value]
  148. return None
  149. def report_config_data(self, ctx: ReportConfigContext) -> dict[str, Any]:
  150. """Return all plugin config data.
  151. Used by mypy to determine if cache needs to be discarded.
  152. """
  153. return self._plugin_data
  154. def _pydantic_model_class_maker_callback(self, ctx: ClassDefContext) -> bool:
  155. transformer = PydanticModelTransformer(ctx.cls, ctx.reason, ctx.api, self.plugin_config)
  156. return transformer.transform()
  157. def _pydantic_model_metaclass_marker_callback(self, ctx: ClassDefContext) -> None:
  158. """Reset dataclass_transform_spec attribute of ModelMetaclass.
  159. Let the plugin handle it. This behavior can be disabled
  160. if 'debug_dataclass_transform' is set to True', for testing purposes.
  161. """
  162. if self.plugin_config.debug_dataclass_transform:
  163. return
  164. info_metaclass = ctx.cls.info.declared_metaclass
  165. assert info_metaclass, "callback not passed from 'get_metaclass_hook'"
  166. if getattr(info_metaclass.type, 'dataclass_transform_spec', None):
  167. info_metaclass.type.dataclass_transform_spec = None
  168. def _pydantic_field_callback(self, ctx: FunctionContext) -> Type:
  169. """Extract the type of the `default` argument from the Field function, and use it as the return type.
  170. In particular:
  171. * Check whether the default and default_factory argument is specified.
  172. * Output an error if both are specified.
  173. * Retrieve the type of the argument which is specified, and use it as return type for the function.
  174. """
  175. default_any_type = ctx.default_return_type
  176. assert ctx.callee_arg_names[0] == 'default', '"default" is no longer first argument in Field()'
  177. assert ctx.callee_arg_names[1] == 'default_factory', '"default_factory" is no longer second argument in Field()'
  178. default_args = ctx.args[0]
  179. default_factory_args = ctx.args[1]
  180. if default_args and default_factory_args:
  181. error_default_and_default_factory_specified(ctx.api, ctx.context)
  182. return default_any_type
  183. if default_args:
  184. default_type = ctx.arg_types[0][0]
  185. default_arg = default_args[0]
  186. # Fallback to default Any type if the field is required
  187. if not isinstance(default_arg, EllipsisExpr):
  188. return default_type
  189. elif default_factory_args:
  190. default_factory_type = ctx.arg_types[1][0]
  191. # Functions which use `ParamSpec` can be overloaded, exposing the callable's types as a parameter
  192. # Pydantic calls the default factory without any argument, so we retrieve the first item
  193. if isinstance(default_factory_type, Overloaded):
  194. default_factory_type = default_factory_type.items[0]
  195. if isinstance(default_factory_type, CallableType):
  196. ret_type = default_factory_type.ret_type
  197. # mypy doesn't think `ret_type` has `args`, you'd think mypy should know,
  198. # add this check in case it varies by version
  199. args = getattr(ret_type, 'args', None)
  200. if args:
  201. if all(isinstance(arg, TypeVarType) for arg in args):
  202. # Looks like the default factory is a type like `list` or `dict`, replace all args with `Any`
  203. ret_type.args = tuple(default_any_type for _ in args) # type: ignore[attr-defined]
  204. return ret_type
  205. return default_any_type
  206. class PydanticPluginConfig:
  207. """A Pydantic mypy plugin config holder.
  208. Attributes:
  209. init_forbid_extra: Whether to add a `**kwargs` at the end of the generated `__init__` signature.
  210. init_typed: Whether to annotate fields in the generated `__init__`.
  211. warn_required_dynamic_aliases: Whether to raise required dynamic aliases error.
  212. debug_dataclass_transform: Whether to not reset `dataclass_transform_spec` attribute
  213. of `ModelMetaclass` for testing purposes.
  214. """
  215. __slots__ = (
  216. 'init_forbid_extra',
  217. 'init_typed',
  218. 'warn_required_dynamic_aliases',
  219. 'debug_dataclass_transform',
  220. )
  221. init_forbid_extra: bool
  222. init_typed: bool
  223. warn_required_dynamic_aliases: bool
  224. debug_dataclass_transform: bool # undocumented
  225. def __init__(self, options: Options) -> None:
  226. if options.config_file is None: # pragma: no cover
  227. return
  228. toml_config = parse_toml(options.config_file)
  229. if toml_config is not None:
  230. config = toml_config.get('tool', {}).get('pydantic-mypy', {})
  231. for key in self.__slots__:
  232. setting = config.get(key, False)
  233. if not isinstance(setting, bool):
  234. raise ValueError(f'Configuration value must be a boolean for key: {key}')
  235. setattr(self, key, setting)
  236. else:
  237. plugin_config = ConfigParser()
  238. plugin_config.read(options.config_file)
  239. for key in self.__slots__:
  240. setting = plugin_config.getboolean(CONFIGFILE_KEY, key, fallback=False)
  241. setattr(self, key, setting)
  242. def to_data(self) -> dict[str, Any]:
  243. """Returns a dict of config names to their values."""
  244. return {key: getattr(self, key) for key in self.__slots__}
  245. def from_attributes_callback(ctx: MethodContext) -> Type:
  246. """Raise an error if from_attributes is not enabled."""
  247. model_type: Instance
  248. ctx_type = ctx.type
  249. if isinstance(ctx_type, TypeType):
  250. ctx_type = ctx_type.item
  251. if isinstance(ctx_type, CallableType) and isinstance(ctx_type.ret_type, Instance):
  252. model_type = ctx_type.ret_type # called on the class
  253. elif isinstance(ctx_type, Instance):
  254. model_type = ctx_type # called on an instance (unusual, but still valid)
  255. else: # pragma: no cover
  256. detail = f'ctx.type: {ctx_type} (of type {ctx_type.__class__.__name__})'
  257. error_unexpected_behavior(detail, ctx.api, ctx.context)
  258. return ctx.default_return_type
  259. pydantic_metadata = model_type.type.metadata.get(METADATA_KEY)
  260. if pydantic_metadata is None:
  261. return ctx.default_return_type
  262. from_attributes = pydantic_metadata.get('config', {}).get('from_attributes')
  263. if from_attributes is not True:
  264. error_from_attributes(model_type.type.name, ctx.api, ctx.context)
  265. return ctx.default_return_type
  266. class PydanticModelField:
  267. """Based on mypy.plugins.dataclasses.DataclassAttribute."""
  268. def __init__(
  269. self,
  270. name: str,
  271. alias: str | None,
  272. has_dynamic_alias: bool,
  273. has_default: bool,
  274. line: int,
  275. column: int,
  276. type: Type | None,
  277. info: TypeInfo,
  278. ):
  279. self.name = name
  280. self.alias = alias
  281. self.has_dynamic_alias = has_dynamic_alias
  282. self.has_default = has_default
  283. self.line = line
  284. self.column = column
  285. self.type = type
  286. self.info = info
  287. def to_argument(self, current_info: TypeInfo, typed: bool, force_optional: bool, use_alias: bool) -> Argument:
  288. """Based on mypy.plugins.dataclasses.DataclassAttribute.to_argument."""
  289. return Argument(
  290. variable=self.to_var(current_info, use_alias),
  291. type_annotation=self.expand_type(current_info) if typed else AnyType(TypeOfAny.explicit),
  292. initializer=None,
  293. kind=ARG_NAMED_OPT if force_optional or self.has_default else ARG_NAMED,
  294. )
  295. def expand_type(self, current_info: TypeInfo) -> Type | None:
  296. """Based on mypy.plugins.dataclasses.DataclassAttribute.expand_type."""
  297. if self.type is not None and self.info.self_type is not None:
  298. # In general, it is not safe to call `expand_type()` during semantic analyzis,
  299. # however this plugin is called very late, so all types should be fully ready.
  300. # Also, it is tricky to avoid eager expansion of Self types here (e.g. because
  301. # we serialize attributes).
  302. return expand_type(self.type, {self.info.self_type.id: fill_typevars(current_info)})
  303. return self.type
  304. def to_var(self, current_info: TypeInfo, use_alias: bool) -> Var:
  305. """Based on mypy.plugins.dataclasses.DataclassAttribute.to_var."""
  306. if use_alias and self.alias is not None:
  307. name = self.alias
  308. else:
  309. name = self.name
  310. return Var(name, self.expand_type(current_info))
  311. def serialize(self) -> JsonDict:
  312. """Based on mypy.plugins.dataclasses.DataclassAttribute.serialize."""
  313. assert self.type
  314. return {
  315. 'name': self.name,
  316. 'alias': self.alias,
  317. 'has_dynamic_alias': self.has_dynamic_alias,
  318. 'has_default': self.has_default,
  319. 'line': self.line,
  320. 'column': self.column,
  321. 'type': self.type.serialize(),
  322. }
  323. @classmethod
  324. def deserialize(cls, info: TypeInfo, data: JsonDict, api: SemanticAnalyzerPluginInterface) -> PydanticModelField:
  325. """Based on mypy.plugins.dataclasses.DataclassAttribute.deserialize."""
  326. data = data.copy()
  327. typ = deserialize_and_fixup_type(data.pop('type'), api)
  328. return cls(type=typ, info=info, **data)
  329. def expand_typevar_from_subtype(self, sub_type: TypeInfo) -> None:
  330. """Expands type vars in the context of a subtype when an attribute is inherited
  331. from a generic super type.
  332. """
  333. if self.type is not None:
  334. self.type = map_type_from_supertype(self.type, sub_type, self.info)
  335. class PydanticModelTransformer:
  336. """Transform the BaseModel subclass according to the plugin settings.
  337. Attributes:
  338. tracked_config_fields: A set of field configs that the plugin has to track their value.
  339. """
  340. tracked_config_fields: set[str] = {
  341. 'extra',
  342. 'frozen',
  343. 'from_attributes',
  344. 'populate_by_name',
  345. 'alias_generator',
  346. }
  347. def __init__(
  348. self,
  349. cls: ClassDef,
  350. reason: Expression | Statement,
  351. api: SemanticAnalyzerPluginInterface,
  352. plugin_config: PydanticPluginConfig,
  353. ) -> None:
  354. self._cls = cls
  355. self._reason = reason
  356. self._api = api
  357. self.plugin_config = plugin_config
  358. def transform(self) -> bool:
  359. """Configures the BaseModel subclass according to the plugin settings.
  360. In particular:
  361. * determines the model config and fields,
  362. * adds a fields-aware signature for the initializer and construct methods
  363. * freezes the class if frozen = True
  364. * stores the fields, config, and if the class is settings in the mypy metadata for access by subclasses
  365. """
  366. info = self._cls.info
  367. config = self.collect_config()
  368. fields = self.collect_fields(config)
  369. if fields is None:
  370. # Some definitions are not ready. We need another pass.
  371. return False
  372. for field in fields:
  373. if field.type is None:
  374. return False
  375. is_settings = any(base.fullname == BASESETTINGS_FULLNAME for base in info.mro[:-1])
  376. self.add_initializer(fields, config, is_settings)
  377. self.add_model_construct_method(fields, config, is_settings)
  378. self.set_frozen(fields, frozen=config.frozen is True)
  379. self.adjust_decorator_signatures()
  380. info.metadata[METADATA_KEY] = {
  381. 'fields': {field.name: field.serialize() for field in fields},
  382. 'config': config.get_values_dict(),
  383. }
  384. return True
  385. def adjust_decorator_signatures(self) -> None:
  386. """When we decorate a function `f` with `pydantic.validator(...)`, `pydantic.field_validator`
  387. or `pydantic.serializer(...)`, mypy sees `f` as a regular method taking a `self` instance,
  388. even though pydantic internally wraps `f` with `classmethod` if necessary.
  389. Teach mypy this by marking any function whose outermost decorator is a `validator()`,
  390. `field_validator()` or `serializer()` call as a `classmethod`.
  391. """
  392. for name, sym in self._cls.info.names.items():
  393. if isinstance(sym.node, Decorator):
  394. first_dec = sym.node.original_decorators[0]
  395. if (
  396. isinstance(first_dec, CallExpr)
  397. and isinstance(first_dec.callee, NameExpr)
  398. and first_dec.callee.fullname in DECORATOR_FULLNAMES
  399. # @model_validator(mode="after") is an exception, it expects a regular method
  400. and not (
  401. first_dec.callee.fullname == MODEL_VALIDATOR_FULLNAME
  402. and any(
  403. first_dec.arg_names[i] == 'mode' and isinstance(arg, StrExpr) and arg.value == 'after'
  404. for i, arg in enumerate(first_dec.args)
  405. )
  406. )
  407. ):
  408. # TODO: Only do this if the first argument of the decorated function is `cls`
  409. sym.node.func.is_class = True
  410. def collect_config(self) -> ModelConfigData: # noqa: C901 (ignore complexity)
  411. """Collects the values of the config attributes that are used by the plugin, accounting for parent classes."""
  412. cls = self._cls
  413. config = ModelConfigData()
  414. has_config_kwargs = False
  415. has_config_from_namespace = False
  416. # Handle `class MyModel(BaseModel, <name>=<expr>, ...):`
  417. for name, expr in cls.keywords.items():
  418. config_data = self.get_config_update(name, expr)
  419. if config_data:
  420. has_config_kwargs = True
  421. config.update(config_data)
  422. # Handle `model_config`
  423. stmt: Statement | None = None
  424. for stmt in cls.defs.body:
  425. if not isinstance(stmt, (AssignmentStmt, ClassDef)):
  426. continue
  427. if isinstance(stmt, AssignmentStmt):
  428. lhs = stmt.lvalues[0]
  429. if not isinstance(lhs, NameExpr) or lhs.name != 'model_config':
  430. continue
  431. if isinstance(stmt.rvalue, CallExpr): # calls to `dict` or `ConfigDict`
  432. for arg_name, arg in zip(stmt.rvalue.arg_names, stmt.rvalue.args):
  433. if arg_name is None:
  434. continue
  435. config.update(self.get_config_update(arg_name, arg))
  436. elif isinstance(stmt.rvalue, DictExpr): # dict literals
  437. for key_expr, value_expr in stmt.rvalue.items:
  438. if not isinstance(key_expr, StrExpr):
  439. continue
  440. config.update(self.get_config_update(key_expr.value, value_expr))
  441. elif isinstance(stmt, ClassDef):
  442. if stmt.name != 'Config': # 'deprecated' Config-class
  443. continue
  444. for substmt in stmt.defs.body:
  445. if not isinstance(substmt, AssignmentStmt):
  446. continue
  447. lhs = substmt.lvalues[0]
  448. if not isinstance(lhs, NameExpr):
  449. continue
  450. config.update(self.get_config_update(lhs.name, substmt.rvalue))
  451. if has_config_kwargs:
  452. self._api.fail(
  453. 'Specifying config in two places is ambiguous, use either Config attribute or class kwargs',
  454. cls,
  455. )
  456. break
  457. has_config_from_namespace = True
  458. if has_config_kwargs or has_config_from_namespace:
  459. if (
  460. stmt
  461. and config.has_alias_generator
  462. and not config.populate_by_name
  463. and self.plugin_config.warn_required_dynamic_aliases
  464. ):
  465. error_required_dynamic_aliases(self._api, stmt)
  466. for info in cls.info.mro[1:]: # 0 is the current class
  467. if METADATA_KEY not in info.metadata:
  468. continue
  469. # Each class depends on the set of fields in its ancestors
  470. self._api.add_plugin_dependency(make_wildcard_trigger(info.fullname))
  471. for name, value in info.metadata[METADATA_KEY]['config'].items():
  472. config.setdefault(name, value)
  473. return config
  474. def collect_fields(self, model_config: ModelConfigData) -> list[PydanticModelField] | None:
  475. """Collects the fields for the model, accounting for parent classes."""
  476. cls = self._cls
  477. # First, collect fields belonging to any class in the MRO, ignoring duplicates.
  478. #
  479. # We iterate through the MRO in reverse because attrs defined in the parent must appear
  480. # earlier in the attributes list than attrs defined in the child. See:
  481. # https://docs.python.org/3/library/dataclasses.html#inheritance
  482. #
  483. # However, we also want fields defined in the subtype to override ones defined
  484. # in the parent. We can implement this via a dict without disrupting the attr order
  485. # because dicts preserve insertion order in Python 3.7+.
  486. found_fields: dict[str, PydanticModelField] = {}
  487. for info in reversed(cls.info.mro[1:-1]): # 0 is the current class, -2 is BaseModel, -1 is object
  488. # if BASEMODEL_METADATA_TAG_KEY in info.metadata and BASEMODEL_METADATA_KEY not in info.metadata:
  489. # # We haven't processed the base class yet. Need another pass.
  490. # return None
  491. if METADATA_KEY not in info.metadata:
  492. continue
  493. # Each class depends on the set of attributes in its dataclass ancestors.
  494. self._api.add_plugin_dependency(make_wildcard_trigger(info.fullname))
  495. for name, data in info.metadata[METADATA_KEY]['fields'].items():
  496. field = PydanticModelField.deserialize(info, data, self._api)
  497. # (The following comment comes directly from the dataclasses plugin)
  498. # TODO: We shouldn't be performing type operations during the main
  499. # semantic analysis pass, since some TypeInfo attributes might
  500. # still be in flux. This should be performed in a later phase.
  501. with state.strict_optional_set(self._api.options.strict_optional):
  502. field.expand_typevar_from_subtype(cls.info)
  503. found_fields[name] = field
  504. sym_node = cls.info.names.get(name)
  505. if sym_node and sym_node.node and not isinstance(sym_node.node, Var):
  506. self._api.fail(
  507. 'BaseModel field may only be overridden by another field',
  508. sym_node.node,
  509. )
  510. # Second, collect fields belonging to the current class.
  511. current_field_names: set[str] = set()
  512. for stmt in self._get_assignment_statements_from_block(cls.defs):
  513. maybe_field = self.collect_field_from_stmt(stmt, model_config)
  514. if maybe_field is not None:
  515. lhs = stmt.lvalues[0]
  516. current_field_names.add(lhs.name)
  517. found_fields[lhs.name] = maybe_field
  518. return list(found_fields.values())
  519. def _get_assignment_statements_from_if_statement(self, stmt: IfStmt) -> Iterator[AssignmentStmt]:
  520. for body in stmt.body:
  521. if not body.is_unreachable:
  522. yield from self._get_assignment_statements_from_block(body)
  523. if stmt.else_body is not None and not stmt.else_body.is_unreachable:
  524. yield from self._get_assignment_statements_from_block(stmt.else_body)
  525. def _get_assignment_statements_from_block(self, block: Block) -> Iterator[AssignmentStmt]:
  526. for stmt in block.body:
  527. if isinstance(stmt, AssignmentStmt):
  528. yield stmt
  529. elif isinstance(stmt, IfStmt):
  530. yield from self._get_assignment_statements_from_if_statement(stmt)
  531. def collect_field_from_stmt( # noqa C901
  532. self, stmt: AssignmentStmt, model_config: ModelConfigData
  533. ) -> PydanticModelField | None:
  534. """Get pydantic model field from statement.
  535. Args:
  536. stmt: The statement.
  537. model_config: Configuration settings for the model.
  538. Returns:
  539. A pydantic model field if it could find the field in statement. Otherwise, `None`.
  540. """
  541. cls = self._cls
  542. lhs = stmt.lvalues[0]
  543. if not isinstance(lhs, NameExpr) or not _fields.is_valid_field_name(lhs.name) or lhs.name == 'model_config':
  544. return None
  545. if not stmt.new_syntax:
  546. if (
  547. isinstance(stmt.rvalue, CallExpr)
  548. and isinstance(stmt.rvalue.callee, CallExpr)
  549. and isinstance(stmt.rvalue.callee.callee, NameExpr)
  550. and stmt.rvalue.callee.callee.fullname in DECORATOR_FULLNAMES
  551. ):
  552. # This is a (possibly-reused) validator or serializer, not a field
  553. # In particular, it looks something like: my_validator = validator('my_field')(f)
  554. # Eventually, we may want to attempt to respect model_config['ignored_types']
  555. return None
  556. # The assignment does not have an annotation, and it's not anything else we recognize
  557. error_untyped_fields(self._api, stmt)
  558. return None
  559. lhs = stmt.lvalues[0]
  560. if not isinstance(lhs, NameExpr):
  561. return None
  562. if not _fields.is_valid_field_name(lhs.name) or lhs.name == 'model_config':
  563. return None
  564. sym = cls.info.names.get(lhs.name)
  565. if sym is None: # pragma: no cover
  566. # This is likely due to a star import (see the dataclasses plugin for a more detailed explanation)
  567. # This is the same logic used in the dataclasses plugin
  568. return None
  569. node = sym.node
  570. if isinstance(node, PlaceholderNode): # pragma: no cover
  571. # See the PlaceholderNode docstring for more detail about how this can occur
  572. # Basically, it is an edge case when dealing with complex import logic
  573. # The dataclasses plugin now asserts this cannot happen, but I'd rather not error if it does..
  574. return None
  575. if isinstance(node, TypeAlias):
  576. self._api.fail(
  577. 'Type aliases inside BaseModel definitions are not supported at runtime',
  578. node,
  579. )
  580. # Skip processing this node. This doesn't match the runtime behaviour,
  581. # but the only alternative would be to modify the SymbolTable,
  582. # and it's a little hairy to do that in a plugin.
  583. return None
  584. if not isinstance(node, Var): # pragma: no cover
  585. # Don't know if this edge case still happens with the `is_valid_field` check above
  586. # but better safe than sorry
  587. # The dataclasses plugin now asserts this cannot happen, but I'd rather not error if it does..
  588. return None
  589. # x: ClassVar[int] is not a field
  590. if node.is_classvar:
  591. return None
  592. # x: InitVar[int] is not supported in BaseModel
  593. node_type = get_proper_type(node.type)
  594. if isinstance(node_type, Instance) and node_type.type.fullname == 'dataclasses.InitVar':
  595. self._api.fail(
  596. 'InitVar is not supported in BaseModel',
  597. node,
  598. )
  599. has_default = self.get_has_default(stmt)
  600. if sym.type is None and node.is_final and node.is_inferred:
  601. # This follows the logic from the dataclasses plugin. The following comment is taken verbatim:
  602. #
  603. # This is a special case, assignment like x: Final = 42 is classified
  604. # annotated above, but mypy strips the `Final` turning it into x = 42.
  605. # We do not support inferred types in dataclasses, so we can try inferring
  606. # type for simple literals, and otherwise require an explicit type
  607. # argument for Final[...].
  608. typ = self._api.analyze_simple_literal_type(stmt.rvalue, is_final=True)
  609. if typ:
  610. node.type = typ
  611. else:
  612. self._api.fail(
  613. 'Need type argument for Final[...] with non-literal default in BaseModel',
  614. stmt,
  615. )
  616. node.type = AnyType(TypeOfAny.from_error)
  617. alias, has_dynamic_alias = self.get_alias_info(stmt)
  618. if has_dynamic_alias and not model_config.populate_by_name and self.plugin_config.warn_required_dynamic_aliases:
  619. error_required_dynamic_aliases(self._api, stmt)
  620. init_type = self._infer_dataclass_attr_init_type(sym, lhs.name, stmt)
  621. return PydanticModelField(
  622. name=lhs.name,
  623. has_dynamic_alias=has_dynamic_alias,
  624. has_default=has_default,
  625. alias=alias,
  626. line=stmt.line,
  627. column=stmt.column,
  628. type=init_type,
  629. info=cls.info,
  630. )
  631. def _infer_dataclass_attr_init_type(self, sym: SymbolTableNode, name: str, context: Context) -> Type | None:
  632. """Infer __init__ argument type for an attribute.
  633. In particular, possibly use the signature of __set__.
  634. """
  635. default = sym.type
  636. if sym.implicit:
  637. return default
  638. t = get_proper_type(sym.type)
  639. # Perform a simple-minded inference from the signature of __set__, if present.
  640. # We can't use mypy.checkmember here, since this plugin runs before type checking.
  641. # We only support some basic scanerios here, which is hopefully sufficient for
  642. # the vast majority of use cases.
  643. if not isinstance(t, Instance):
  644. return default
  645. setter = t.type.get('__set__')
  646. if setter:
  647. if isinstance(setter.node, FuncDef):
  648. super_info = t.type.get_containing_type_info('__set__')
  649. assert super_info
  650. if setter.type:
  651. setter_type = get_proper_type(map_type_from_supertype(setter.type, t.type, super_info))
  652. else:
  653. return AnyType(TypeOfAny.unannotated)
  654. if isinstance(setter_type, CallableType) and setter_type.arg_kinds == [
  655. ARG_POS,
  656. ARG_POS,
  657. ARG_POS,
  658. ]:
  659. return expand_type_by_instance(setter_type.arg_types[2], t)
  660. else:
  661. self._api.fail(f'Unsupported signature for "__set__" in "{t.type.name}"', context)
  662. else:
  663. self._api.fail(f'Unsupported "__set__" in "{t.type.name}"', context)
  664. return default
  665. def add_initializer(self, fields: list[PydanticModelField], config: ModelConfigData, is_settings: bool) -> None:
  666. """Adds a fields-aware `__init__` method to the class.
  667. The added `__init__` will be annotated with types vs. all `Any` depending on the plugin settings.
  668. """
  669. if '__init__' in self._cls.info.names and not self._cls.info.names['__init__'].plugin_generated:
  670. return # Don't generate an __init__ if one already exists
  671. typed = self.plugin_config.init_typed
  672. use_alias = config.populate_by_name is not True
  673. requires_dynamic_aliases = bool(config.has_alias_generator and not config.populate_by_name)
  674. with state.strict_optional_set(self._api.options.strict_optional):
  675. args = self.get_field_arguments(
  676. fields,
  677. typed=typed,
  678. requires_dynamic_aliases=requires_dynamic_aliases,
  679. use_alias=use_alias,
  680. is_settings=is_settings,
  681. )
  682. if is_settings:
  683. base_settings_node = self._api.lookup_fully_qualified(BASESETTINGS_FULLNAME).node
  684. if '__init__' in base_settings_node.names:
  685. base_settings_init_node = base_settings_node.names['__init__'].node
  686. if base_settings_init_node is not None and base_settings_init_node.type is not None:
  687. func_type = base_settings_init_node.type
  688. for arg_idx, arg_name in enumerate(func_type.arg_names):
  689. if arg_name.startswith('__') or not arg_name.startswith('_'):
  690. continue
  691. analyzed_variable_type = self._api.anal_type(func_type.arg_types[arg_idx])
  692. variable = Var(arg_name, analyzed_variable_type)
  693. args.append(Argument(variable, analyzed_variable_type, None, ARG_OPT))
  694. if not self.should_init_forbid_extra(fields, config):
  695. var = Var('kwargs')
  696. args.append(Argument(var, AnyType(TypeOfAny.explicit), None, ARG_STAR2))
  697. add_method(self._api, self._cls, '__init__', args=args, return_type=NoneType())
  698. def add_model_construct_method(
  699. self, fields: list[PydanticModelField], config: ModelConfigData, is_settings: bool
  700. ) -> None:
  701. """Adds a fully typed `model_construct` classmethod to the class.
  702. Similar to the fields-aware __init__ method, but always uses the field names (not aliases),
  703. and does not treat settings fields as optional.
  704. """
  705. set_str = self._api.named_type(f'{BUILTINS_NAME}.set', [self._api.named_type(f'{BUILTINS_NAME}.str')])
  706. optional_set_str = UnionType([set_str, NoneType()])
  707. fields_set_argument = Argument(Var('_fields_set', optional_set_str), optional_set_str, None, ARG_OPT)
  708. with state.strict_optional_set(self._api.options.strict_optional):
  709. args = self.get_field_arguments(
  710. fields, typed=True, requires_dynamic_aliases=False, use_alias=False, is_settings=is_settings
  711. )
  712. if not self.should_init_forbid_extra(fields, config):
  713. var = Var('kwargs')
  714. args.append(Argument(var, AnyType(TypeOfAny.explicit), None, ARG_STAR2))
  715. args = [fields_set_argument] + args
  716. add_method(
  717. self._api,
  718. self._cls,
  719. 'model_construct',
  720. args=args,
  721. return_type=fill_typevars(self._cls.info),
  722. is_classmethod=True,
  723. )
  724. def set_frozen(self, fields: list[PydanticModelField], frozen: bool) -> None:
  725. """Marks all fields as properties so that attempts to set them trigger mypy errors.
  726. This is the same approach used by the attrs and dataclasses plugins.
  727. """
  728. info = self._cls.info
  729. for field in fields:
  730. sym_node = info.names.get(field.name)
  731. if sym_node is not None:
  732. var = sym_node.node
  733. if isinstance(var, Var):
  734. var.is_property = frozen
  735. elif isinstance(var, PlaceholderNode) and not self._api.final_iteration:
  736. # See https://github.com/pydantic/pydantic/issues/5191 to hit this branch for test coverage
  737. self._api.defer()
  738. else: # pragma: no cover
  739. # I don't know whether it's possible to hit this branch, but I've added it for safety
  740. try:
  741. var_str = str(var)
  742. except TypeError:
  743. # This happens for PlaceholderNode; perhaps it will happen for other types in the future..
  744. var_str = repr(var)
  745. detail = f'sym_node.node: {var_str} (of type {var.__class__})'
  746. error_unexpected_behavior(detail, self._api, self._cls)
  747. else:
  748. var = field.to_var(info, use_alias=False)
  749. var.info = info
  750. var.is_property = frozen
  751. var._fullname = info.fullname + '.' + var.name
  752. info.names[var.name] = SymbolTableNode(MDEF, var)
  753. def get_config_update(self, name: str, arg: Expression) -> ModelConfigData | None:
  754. """Determines the config update due to a single kwarg in the ConfigDict definition.
  755. Warns if a tracked config attribute is set to a value the plugin doesn't know how to interpret (e.g., an int)
  756. """
  757. if name not in self.tracked_config_fields:
  758. return None
  759. if name == 'extra':
  760. if isinstance(arg, StrExpr):
  761. forbid_extra = arg.value == 'forbid'
  762. elif isinstance(arg, MemberExpr):
  763. forbid_extra = arg.name == 'forbid'
  764. else:
  765. error_invalid_config_value(name, self._api, arg)
  766. return None
  767. return ModelConfigData(forbid_extra=forbid_extra)
  768. if name == 'alias_generator':
  769. has_alias_generator = True
  770. if isinstance(arg, NameExpr) and arg.fullname == 'builtins.None':
  771. has_alias_generator = False
  772. return ModelConfigData(has_alias_generator=has_alias_generator)
  773. if isinstance(arg, NameExpr) and arg.fullname in ('builtins.True', 'builtins.False'):
  774. return ModelConfigData(**{name: arg.fullname == 'builtins.True'})
  775. error_invalid_config_value(name, self._api, arg)
  776. return None
  777. @staticmethod
  778. def get_has_default(stmt: AssignmentStmt) -> bool:
  779. """Returns a boolean indicating whether the field defined in `stmt` is a required field."""
  780. expr = stmt.rvalue
  781. if isinstance(expr, TempNode):
  782. # TempNode means annotation-only, so has no default
  783. return False
  784. if isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME:
  785. # The "default value" is a call to `Field`; at this point, the field has a default if and only if:
  786. # * there is a positional argument that is not `...`
  787. # * there is a keyword argument named "default" that is not `...`
  788. # * there is a "default_factory" that is not `None`
  789. for arg, name in zip(expr.args, expr.arg_names):
  790. # If name is None, then this arg is the default because it is the only positional argument.
  791. if name is None or name == 'default':
  792. return arg.__class__ is not EllipsisExpr
  793. if name == 'default_factory':
  794. return not (isinstance(arg, NameExpr) and arg.fullname == 'builtins.None')
  795. return False
  796. # Has no default if the "default value" is Ellipsis (i.e., `field_name: Annotation = ...`)
  797. return not isinstance(expr, EllipsisExpr)
  798. @staticmethod
  799. def get_alias_info(stmt: AssignmentStmt) -> tuple[str | None, bool]:
  800. """Returns a pair (alias, has_dynamic_alias), extracted from the declaration of the field defined in `stmt`.
  801. `has_dynamic_alias` is True if and only if an alias is provided, but not as a string literal.
  802. If `has_dynamic_alias` is True, `alias` will be None.
  803. """
  804. expr = stmt.rvalue
  805. if isinstance(expr, TempNode):
  806. # TempNode means annotation-only
  807. return None, False
  808. if not (
  809. isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME
  810. ):
  811. # Assigned value is not a call to pydantic.fields.Field
  812. return None, False
  813. for i, arg_name in enumerate(expr.arg_names):
  814. if arg_name != 'alias':
  815. continue
  816. arg = expr.args[i]
  817. if isinstance(arg, StrExpr):
  818. return arg.value, False
  819. else:
  820. return None, True
  821. return None, False
  822. def get_field_arguments(
  823. self,
  824. fields: list[PydanticModelField],
  825. typed: bool,
  826. use_alias: bool,
  827. requires_dynamic_aliases: bool,
  828. is_settings: bool,
  829. ) -> list[Argument]:
  830. """Helper function used during the construction of the `__init__` and `model_construct` method signatures.
  831. Returns a list of mypy Argument instances for use in the generated signatures.
  832. """
  833. info = self._cls.info
  834. arguments = [
  835. field.to_argument(
  836. info, typed=typed, force_optional=requires_dynamic_aliases or is_settings, use_alias=use_alias
  837. )
  838. for field in fields
  839. if not (use_alias and field.has_dynamic_alias)
  840. ]
  841. return arguments
  842. def should_init_forbid_extra(self, fields: list[PydanticModelField], config: ModelConfigData) -> bool:
  843. """Indicates whether the generated `__init__` should get a `**kwargs` at the end of its signature.
  844. We disallow arbitrary kwargs if the extra config setting is "forbid", or if the plugin config says to,
  845. *unless* a required dynamic alias is present (since then we can't determine a valid signature).
  846. """
  847. if not config.populate_by_name:
  848. if self.is_dynamic_alias_present(fields, bool(config.has_alias_generator)):
  849. return False
  850. if config.forbid_extra:
  851. return True
  852. return self.plugin_config.init_forbid_extra
  853. @staticmethod
  854. def is_dynamic_alias_present(fields: list[PydanticModelField], has_alias_generator: bool) -> bool:
  855. """Returns whether any fields on the model have a "dynamic alias", i.e., an alias that cannot be
  856. determined during static analysis.
  857. """
  858. for field in fields:
  859. if field.has_dynamic_alias:
  860. return True
  861. if has_alias_generator:
  862. for field in fields:
  863. if field.alias is None:
  864. return True
  865. return False
  866. class ModelConfigData:
  867. """Pydantic mypy plugin model config class."""
  868. def __init__(
  869. self,
  870. forbid_extra: bool | None = None,
  871. frozen: bool | None = None,
  872. from_attributes: bool | None = None,
  873. populate_by_name: bool | None = None,
  874. has_alias_generator: bool | None = None,
  875. ):
  876. self.forbid_extra = forbid_extra
  877. self.frozen = frozen
  878. self.from_attributes = from_attributes
  879. self.populate_by_name = populate_by_name
  880. self.has_alias_generator = has_alias_generator
  881. def get_values_dict(self) -> dict[str, Any]:
  882. """Returns a dict of Pydantic model config names to their values.
  883. It includes the config if config value is not `None`.
  884. """
  885. return {k: v for k, v in self.__dict__.items() if v is not None}
  886. def update(self, config: ModelConfigData | None) -> None:
  887. """Update Pydantic model config values."""
  888. if config is None:
  889. return
  890. for k, v in config.get_values_dict().items():
  891. setattr(self, k, v)
  892. def setdefault(self, key: str, value: Any) -> None:
  893. """Set default value for Pydantic model config if config value is `None`."""
  894. if getattr(self, key) is None:
  895. setattr(self, key, value)
  896. ERROR_ORM = ErrorCode('pydantic-orm', 'Invalid from_attributes call', 'Pydantic')
  897. ERROR_CONFIG = ErrorCode('pydantic-config', 'Invalid config value', 'Pydantic')
  898. ERROR_ALIAS = ErrorCode('pydantic-alias', 'Dynamic alias disallowed', 'Pydantic')
  899. ERROR_UNEXPECTED = ErrorCode('pydantic-unexpected', 'Unexpected behavior', 'Pydantic')
  900. ERROR_UNTYPED = ErrorCode('pydantic-field', 'Untyped field disallowed', 'Pydantic')
  901. ERROR_FIELD_DEFAULTS = ErrorCode('pydantic-field', 'Invalid Field defaults', 'Pydantic')
  902. def error_from_attributes(model_name: str, api: CheckerPluginInterface, context: Context) -> None:
  903. """Emits an error when the model does not have `from_attributes=True`."""
  904. api.fail(f'"{model_name}" does not have from_attributes=True', context, code=ERROR_ORM)
  905. def error_invalid_config_value(name: str, api: SemanticAnalyzerPluginInterface, context: Context) -> None:
  906. """Emits an error when the config value is invalid."""
  907. api.fail(f'Invalid value for "Config.{name}"', context, code=ERROR_CONFIG)
  908. def error_required_dynamic_aliases(api: SemanticAnalyzerPluginInterface, context: Context) -> None:
  909. """Emits required dynamic aliases error.
  910. This will be called when `warn_required_dynamic_aliases=True`.
  911. """
  912. api.fail('Required dynamic aliases disallowed', context, code=ERROR_ALIAS)
  913. def error_unexpected_behavior(
  914. detail: str, api: CheckerPluginInterface | SemanticAnalyzerPluginInterface, context: Context
  915. ) -> None: # pragma: no cover
  916. """Emits unexpected behavior error."""
  917. # Can't think of a good way to test this, but I confirmed it renders as desired by adding to a non-error path
  918. link = 'https://github.com/pydantic/pydantic/issues/new/choose'
  919. full_message = f'The pydantic mypy plugin ran into unexpected behavior: {detail}\n'
  920. full_message += f'Please consider reporting this bug at {link} so we can try to fix it!'
  921. api.fail(full_message, context, code=ERROR_UNEXPECTED)
  922. def error_untyped_fields(api: SemanticAnalyzerPluginInterface, context: Context) -> None:
  923. """Emits an error when there is an untyped field in the model."""
  924. api.fail('Untyped fields disallowed', context, code=ERROR_UNTYPED)
  925. def error_default_and_default_factory_specified(api: CheckerPluginInterface, context: Context) -> None:
  926. """Emits an error when `Field` has both `default` and `default_factory` together."""
  927. api.fail('Field default and default_factory cannot be specified together', context, code=ERROR_FIELD_DEFAULTS)
  928. def add_method(
  929. api: SemanticAnalyzerPluginInterface | CheckerPluginInterface,
  930. cls: ClassDef,
  931. name: str,
  932. args: list[Argument],
  933. return_type: Type,
  934. self_type: Type | None = None,
  935. tvar_def: TypeVarDef | None = None,
  936. is_classmethod: bool = False,
  937. ) -> None:
  938. """Very closely related to `mypy.plugins.common.add_method_to_class`, with a few pydantic-specific changes."""
  939. info = cls.info
  940. # First remove any previously generated methods with the same name
  941. # to avoid clashes and problems in the semantic analyzer.
  942. if name in info.names:
  943. sym = info.names[name]
  944. if sym.plugin_generated and isinstance(sym.node, FuncDef):
  945. cls.defs.body.remove(sym.node) # pragma: no cover
  946. if isinstance(api, SemanticAnalyzerPluginInterface):
  947. function_type = api.named_type('builtins.function')
  948. else:
  949. function_type = api.named_generic_type('builtins.function', [])
  950. if is_classmethod:
  951. self_type = self_type or TypeType(fill_typevars(info))
  952. first = [Argument(Var('_cls'), self_type, None, ARG_POS, True)]
  953. else:
  954. self_type = self_type or fill_typevars(info)
  955. first = [Argument(Var('__pydantic_self__'), self_type, None, ARG_POS)]
  956. args = first + args
  957. arg_types, arg_names, arg_kinds = [], [], []
  958. for arg in args:
  959. assert arg.type_annotation, 'All arguments must be fully typed.'
  960. arg_types.append(arg.type_annotation)
  961. arg_names.append(arg.variable.name)
  962. arg_kinds.append(arg.kind)
  963. signature = CallableType(arg_types, arg_kinds, arg_names, return_type, function_type)
  964. if tvar_def:
  965. signature.variables = [tvar_def]
  966. func = FuncDef(name, args, Block([PassStmt()]))
  967. func.info = info
  968. func.type = set_callable_name(signature, func)
  969. func.is_class = is_classmethod
  970. func._fullname = info.fullname + '.' + name
  971. func.line = info.line
  972. # NOTE: we would like the plugin generated node to dominate, but we still
  973. # need to keep any existing definitions so they get semantically analyzed.
  974. if name in info.names:
  975. # Get a nice unique name instead.
  976. r_name = get_unique_redefinition_name(name, info.names)
  977. info.names[r_name] = info.names[name]
  978. # Add decorator for is_classmethod
  979. # The dataclasses plugin claims this is unnecessary for classmethods, but not including it results in a
  980. # signature incompatible with the superclass, which causes mypy errors to occur for every subclass of BaseModel.
  981. if is_classmethod:
  982. func.is_decorated = True
  983. v = Var(name, func.type)
  984. v.info = info
  985. v._fullname = func._fullname
  986. v.is_classmethod = True
  987. dec = Decorator(func, [NameExpr('classmethod')], v)
  988. dec.line = info.line
  989. sym = SymbolTableNode(MDEF, dec)
  990. else:
  991. sym = SymbolTableNode(MDEF, func)
  992. sym.plugin_generated = True
  993. info.names[name] = sym
  994. info.defn.defs.body.append(func)
  995. def parse_toml(config_file: str) -> dict[str, Any] | None:
  996. """Returns a dict of config keys to values.
  997. It reads configs from toml file and returns `None` if the file is not a toml file.
  998. """
  999. if not config_file.endswith('.toml'):
  1000. return None
  1001. if sys.version_info >= (3, 11):
  1002. import tomllib as toml_
  1003. else:
  1004. try:
  1005. import tomli as toml_
  1006. except ImportError: # pragma: no cover
  1007. import warnings
  1008. warnings.warn('No TOML parser installed, cannot read configuration from `pyproject.toml`.')
  1009. return None
  1010. with open(config_file, 'rb') as rf:
  1011. return toml_.load(rf)