mypy.py 55 KB

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