Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

1381 řádky
58 KiB

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