You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

740 lines
29 KiB

  1. from configparser import ConfigParser
  2. from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type as TypingType, Union
  3. from mypy.errorcodes import ErrorCode
  4. from mypy.nodes import (
  5. ARG_NAMED,
  6. ARG_NAMED_OPT,
  7. ARG_OPT,
  8. ARG_POS,
  9. ARG_STAR2,
  10. MDEF,
  11. Argument,
  12. AssignmentStmt,
  13. Block,
  14. CallExpr,
  15. ClassDef,
  16. Context,
  17. Decorator,
  18. EllipsisExpr,
  19. FuncBase,
  20. FuncDef,
  21. JsonDict,
  22. MemberExpr,
  23. NameExpr,
  24. PassStmt,
  25. PlaceholderNode,
  26. RefExpr,
  27. StrExpr,
  28. SymbolNode,
  29. SymbolTableNode,
  30. TempNode,
  31. TypeInfo,
  32. TypeVarExpr,
  33. Var,
  34. )
  35. from mypy.options import Options
  36. from mypy.plugin import CheckerPluginInterface, ClassDefContext, MethodContext, Plugin, SemanticAnalyzerPluginInterface
  37. from mypy.plugins import dataclasses
  38. from mypy.semanal import set_callable_name # type: ignore
  39. from mypy.server.trigger import make_wildcard_trigger
  40. from mypy.types import (
  41. AnyType,
  42. CallableType,
  43. Instance,
  44. NoneType,
  45. Type,
  46. TypeOfAny,
  47. TypeType,
  48. TypeVarType,
  49. UnionType,
  50. get_proper_type,
  51. )
  52. from mypy.typevars import fill_typevars
  53. from mypy.util import get_unique_redefinition_name
  54. from mypy.version import __version__ as mypy_version
  55. from pydantic.utils import is_valid_field
  56. try:
  57. from mypy.types import TypeVarDef # type: ignore[attr-defined]
  58. except ImportError: # pragma: no cover
  59. # Backward-compatible with TypeVarDef from Mypy 0.910.
  60. from mypy.types import TypeVarType as TypeVarDef
  61. CONFIGFILE_KEY = 'pydantic-mypy'
  62. METADATA_KEY = 'pydantic-mypy-metadata'
  63. BASEMODEL_FULLNAME = 'pydantic.main.BaseModel'
  64. BASESETTINGS_FULLNAME = 'pydantic.env_settings.BaseSettings'
  65. FIELD_FULLNAME = 'pydantic.fields.Field'
  66. DATACLASS_FULLNAME = 'pydantic.dataclasses.dataclass'
  67. BUILTINS_NAME = 'builtins' if float(mypy_version) >= 0.930 else '__builtins__'
  68. def plugin(version: str) -> 'TypingType[Plugin]':
  69. """
  70. `version` is the mypy version string
  71. We might want to use this to print a warning if the mypy version being used is
  72. newer, or especially older, than we expect (or need).
  73. """
  74. return PydanticPlugin
  75. class PydanticPlugin(Plugin):
  76. def __init__(self, options: Options) -> None:
  77. self.plugin_config = PydanticPluginConfig(options)
  78. super().__init__(options)
  79. def get_base_class_hook(self, fullname: str) -> 'Optional[Callable[[ClassDefContext], None]]':
  80. sym = self.lookup_fully_qualified(fullname)
  81. if sym and isinstance(sym.node, TypeInfo): # pragma: no branch
  82. # No branching may occur if the mypy cache has not been cleared
  83. if any(get_fullname(base) == BASEMODEL_FULLNAME for base in sym.node.mro):
  84. return self._pydantic_model_class_maker_callback
  85. return None
  86. def get_method_hook(self, fullname: str) -> Optional[Callable[[MethodContext], Type]]:
  87. if fullname.endswith('.from_orm'):
  88. return from_orm_callback
  89. return None
  90. def get_class_decorator_hook(self, fullname: str) -> Optional[Callable[[ClassDefContext], None]]:
  91. if fullname == DATACLASS_FULLNAME:
  92. return dataclasses.dataclass_class_maker_callback
  93. return None
  94. def _pydantic_model_class_maker_callback(self, ctx: ClassDefContext) -> None:
  95. transformer = PydanticModelTransformer(ctx, self.plugin_config)
  96. transformer.transform()
  97. class PydanticPluginConfig:
  98. __slots__ = ('init_forbid_extra', 'init_typed', 'warn_required_dynamic_aliases', 'warn_untyped_fields')
  99. init_forbid_extra: bool
  100. init_typed: bool
  101. warn_required_dynamic_aliases: bool
  102. warn_untyped_fields: bool
  103. def __init__(self, options: Options) -> None:
  104. if options.config_file is None: # pragma: no cover
  105. return
  106. toml_config = parse_toml(options.config_file)
  107. if toml_config is not None:
  108. config = toml_config.get('tool', {}).get('pydantic-mypy', {})
  109. for key in self.__slots__:
  110. setting = config.get(key, False)
  111. if not isinstance(setting, bool):
  112. raise ValueError(f'Configuration value must be a boolean for key: {key}')
  113. setattr(self, key, setting)
  114. else:
  115. plugin_config = ConfigParser()
  116. plugin_config.read(options.config_file)
  117. for key in self.__slots__:
  118. setting = plugin_config.getboolean(CONFIGFILE_KEY, key, fallback=False)
  119. setattr(self, key, setting)
  120. def from_orm_callback(ctx: MethodContext) -> Type:
  121. """
  122. Raise an error if orm_mode is not enabled
  123. """
  124. model_type: Instance
  125. if isinstance(ctx.type, CallableType) and isinstance(ctx.type.ret_type, Instance):
  126. model_type = ctx.type.ret_type # called on the class
  127. elif isinstance(ctx.type, Instance):
  128. model_type = ctx.type # called on an instance (unusual, but still valid)
  129. else: # pragma: no cover
  130. detail = f'ctx.type: {ctx.type} (of type {ctx.type.__class__.__name__})'
  131. error_unexpected_behavior(detail, ctx.api, ctx.context)
  132. return ctx.default_return_type
  133. pydantic_metadata = model_type.type.metadata.get(METADATA_KEY)
  134. if pydantic_metadata is None:
  135. return ctx.default_return_type
  136. orm_mode = pydantic_metadata.get('config', {}).get('orm_mode')
  137. if orm_mode is not True:
  138. error_from_orm(get_name(model_type.type), ctx.api, ctx.context)
  139. return ctx.default_return_type
  140. class PydanticModelTransformer:
  141. tracked_config_fields: Set[str] = {
  142. 'extra',
  143. 'allow_mutation',
  144. 'frozen',
  145. 'orm_mode',
  146. 'allow_population_by_field_name',
  147. 'alias_generator',
  148. }
  149. def __init__(self, ctx: ClassDefContext, plugin_config: PydanticPluginConfig) -> None:
  150. self._ctx = ctx
  151. self.plugin_config = plugin_config
  152. def transform(self) -> None:
  153. """
  154. Configures the BaseModel subclass according to the plugin settings.
  155. In particular:
  156. * determines the model config and fields,
  157. * adds a fields-aware signature for the initializer and construct methods
  158. * freezes the class if allow_mutation = False or frozen = True
  159. * stores the fields, config, and if the class is settings in the mypy metadata for access by subclasses
  160. """
  161. ctx = self._ctx
  162. info = self._ctx.cls.info
  163. config = self.collect_config()
  164. fields = self.collect_fields(config)
  165. for field in fields:
  166. if info[field.name].type is None:
  167. if not ctx.api.final_iteration:
  168. ctx.api.defer()
  169. is_settings = any(get_fullname(base) == BASESETTINGS_FULLNAME for base in info.mro[:-1])
  170. self.add_initializer(fields, config, is_settings)
  171. self.add_construct_method(fields)
  172. self.set_frozen(fields, frozen=config.allow_mutation is False or config.frozen is True)
  173. info.metadata[METADATA_KEY] = {
  174. 'fields': {field.name: field.serialize() for field in fields},
  175. 'config': config.set_values_dict(),
  176. }
  177. def collect_config(self) -> 'ModelConfigData':
  178. """
  179. Collects the values of the config attributes that are used by the plugin, accounting for parent classes.
  180. """
  181. ctx = self._ctx
  182. cls = ctx.cls
  183. config = ModelConfigData()
  184. for stmt in cls.defs.body:
  185. if not isinstance(stmt, ClassDef):
  186. continue
  187. if stmt.name == 'Config':
  188. for substmt in stmt.defs.body:
  189. if not isinstance(substmt, AssignmentStmt):
  190. continue
  191. config.update(self.get_config_update(substmt))
  192. if (
  193. config.has_alias_generator
  194. and not config.allow_population_by_field_name
  195. and self.plugin_config.warn_required_dynamic_aliases
  196. ):
  197. error_required_dynamic_aliases(ctx.api, stmt)
  198. for info in cls.info.mro[1:]: # 0 is the current class
  199. if METADATA_KEY not in info.metadata:
  200. continue
  201. # Each class depends on the set of fields in its ancestors
  202. ctx.api.add_plugin_dependency(make_wildcard_trigger(get_fullname(info)))
  203. for name, value in info.metadata[METADATA_KEY]['config'].items():
  204. config.setdefault(name, value)
  205. return config
  206. def collect_fields(self, model_config: 'ModelConfigData') -> List['PydanticModelField']:
  207. """
  208. Collects the fields for the model, accounting for parent classes
  209. """
  210. # First, collect fields belonging to the current class.
  211. ctx = self._ctx
  212. cls = self._ctx.cls
  213. fields = [] # type: List[PydanticModelField]
  214. known_fields = set() # type: Set[str]
  215. for stmt in cls.defs.body:
  216. if not isinstance(stmt, AssignmentStmt): # `and stmt.new_syntax` to require annotation
  217. continue
  218. lhs = stmt.lvalues[0]
  219. if not isinstance(lhs, NameExpr) or not is_valid_field(lhs.name):
  220. continue
  221. if not stmt.new_syntax and self.plugin_config.warn_untyped_fields:
  222. error_untyped_fields(ctx.api, stmt)
  223. # if lhs.name == '__config__': # BaseConfig not well handled; I'm not sure why yet
  224. # continue
  225. sym = cls.info.names.get(lhs.name)
  226. if sym is None: # pragma: no cover
  227. # This is likely due to a star import (see the dataclasses plugin for a more detailed explanation)
  228. # This is the same logic used in the dataclasses plugin
  229. continue
  230. node = sym.node
  231. if isinstance(node, PlaceholderNode): # pragma: no cover
  232. # See the PlaceholderNode docstring for more detail about how this can occur
  233. # Basically, it is an edge case when dealing with complex import logic
  234. # This is the same logic used in the dataclasses plugin
  235. continue
  236. if not isinstance(node, Var): # pragma: no cover
  237. # Don't know if this edge case still happens with the `is_valid_field` check above
  238. # but better safe than sorry
  239. continue
  240. # x: ClassVar[int] is ignored by dataclasses.
  241. if node.is_classvar:
  242. continue
  243. is_required = self.get_is_required(cls, stmt, lhs)
  244. alias, has_dynamic_alias = self.get_alias_info(stmt)
  245. if (
  246. has_dynamic_alias
  247. and not model_config.allow_population_by_field_name
  248. and self.plugin_config.warn_required_dynamic_aliases
  249. ):
  250. error_required_dynamic_aliases(ctx.api, stmt)
  251. fields.append(
  252. PydanticModelField(
  253. name=lhs.name,
  254. is_required=is_required,
  255. alias=alias,
  256. has_dynamic_alias=has_dynamic_alias,
  257. line=stmt.line,
  258. column=stmt.column,
  259. )
  260. )
  261. known_fields.add(lhs.name)
  262. all_fields = fields.copy()
  263. for info in cls.info.mro[1:]: # 0 is the current class, -2 is BaseModel, -1 is object
  264. if METADATA_KEY not in info.metadata:
  265. continue
  266. superclass_fields = []
  267. # Each class depends on the set of fields in its ancestors
  268. ctx.api.add_plugin_dependency(make_wildcard_trigger(get_fullname(info)))
  269. for name, data in info.metadata[METADATA_KEY]['fields'].items():
  270. if name not in known_fields:
  271. field = PydanticModelField.deserialize(info, data)
  272. known_fields.add(name)
  273. superclass_fields.append(field)
  274. else:
  275. (field,) = [a for a in all_fields if a.name == name]
  276. all_fields.remove(field)
  277. superclass_fields.append(field)
  278. all_fields = superclass_fields + all_fields
  279. return all_fields
  280. def add_initializer(self, fields: List['PydanticModelField'], config: 'ModelConfigData', is_settings: bool) -> None:
  281. """
  282. Adds a fields-aware `__init__` method to the class.
  283. The added `__init__` will be annotated with types vs. all `Any` depending on the plugin settings.
  284. """
  285. ctx = self._ctx
  286. typed = self.plugin_config.init_typed
  287. use_alias = config.allow_population_by_field_name is not True
  288. force_all_optional = is_settings or bool(
  289. config.has_alias_generator and not config.allow_population_by_field_name
  290. )
  291. init_arguments = self.get_field_arguments(
  292. fields, typed=typed, force_all_optional=force_all_optional, use_alias=use_alias
  293. )
  294. if not self.should_init_forbid_extra(fields, config):
  295. var = Var('kwargs')
  296. init_arguments.append(Argument(var, AnyType(TypeOfAny.explicit), None, ARG_STAR2))
  297. add_method(ctx, '__init__', init_arguments, NoneType())
  298. def add_construct_method(self, fields: List['PydanticModelField']) -> None:
  299. """
  300. Adds a fully typed `construct` classmethod to the class.
  301. Similar to the fields-aware __init__ method, but always uses the field names (not aliases),
  302. and does not treat settings fields as optional.
  303. """
  304. ctx = self._ctx
  305. set_str = ctx.api.named_type(f'{BUILTINS_NAME}.set', [ctx.api.named_type(f'{BUILTINS_NAME}.str')])
  306. optional_set_str = UnionType([set_str, NoneType()])
  307. fields_set_argument = Argument(Var('_fields_set', optional_set_str), optional_set_str, None, ARG_OPT)
  308. construct_arguments = self.get_field_arguments(fields, typed=True, force_all_optional=False, use_alias=False)
  309. construct_arguments = [fields_set_argument] + construct_arguments
  310. obj_type = ctx.api.named_type(f'{BUILTINS_NAME}.object')
  311. self_tvar_name = '_PydanticBaseModel' # Make sure it does not conflict with other names in the class
  312. tvar_fullname = ctx.cls.fullname + '.' + self_tvar_name
  313. tvd = TypeVarDef(self_tvar_name, tvar_fullname, -1, [], obj_type)
  314. self_tvar_expr = TypeVarExpr(self_tvar_name, tvar_fullname, [], obj_type)
  315. ctx.cls.info.names[self_tvar_name] = SymbolTableNode(MDEF, self_tvar_expr)
  316. # Backward-compatible with TypeVarDef from Mypy 0.910.
  317. if isinstance(tvd, TypeVarType):
  318. self_type = tvd
  319. else:
  320. self_type = TypeVarType(tvd) # type: ignore[call-arg]
  321. add_method(
  322. ctx,
  323. 'construct',
  324. construct_arguments,
  325. return_type=self_type,
  326. self_type=self_type,
  327. tvar_def=tvd,
  328. is_classmethod=True,
  329. )
  330. def set_frozen(self, fields: List['PydanticModelField'], frozen: bool) -> None:
  331. """
  332. Marks all fields as properties so that attempts to set them trigger mypy errors.
  333. This is the same approach used by the attrs and dataclasses plugins.
  334. """
  335. info = self._ctx.cls.info
  336. for field in fields:
  337. sym_node = info.names.get(field.name)
  338. if sym_node is not None:
  339. var = sym_node.node
  340. assert isinstance(var, Var)
  341. var.is_property = frozen
  342. else:
  343. var = field.to_var(info, use_alias=False)
  344. var.info = info
  345. var.is_property = frozen
  346. var._fullname = get_fullname(info) + '.' + get_name(var)
  347. info.names[get_name(var)] = SymbolTableNode(MDEF, var)
  348. def get_config_update(self, substmt: AssignmentStmt) -> Optional['ModelConfigData']:
  349. """
  350. Determines the config update due to a single statement in the Config class definition.
  351. Warns if a tracked config attribute is set to a value the plugin doesn't know how to interpret (e.g., an int)
  352. """
  353. lhs = substmt.lvalues[0]
  354. if not (isinstance(lhs, NameExpr) and lhs.name in self.tracked_config_fields):
  355. return None
  356. if lhs.name == 'extra':
  357. if isinstance(substmt.rvalue, StrExpr):
  358. forbid_extra = substmt.rvalue.value == 'forbid'
  359. elif isinstance(substmt.rvalue, MemberExpr):
  360. forbid_extra = substmt.rvalue.name == 'forbid'
  361. else:
  362. error_invalid_config_value(lhs.name, self._ctx.api, substmt)
  363. return None
  364. return ModelConfigData(forbid_extra=forbid_extra)
  365. if lhs.name == 'alias_generator':
  366. has_alias_generator = True
  367. if isinstance(substmt.rvalue, NameExpr) and substmt.rvalue.fullname == 'builtins.None':
  368. has_alias_generator = False
  369. return ModelConfigData(has_alias_generator=has_alias_generator)
  370. if isinstance(substmt.rvalue, NameExpr) and substmt.rvalue.fullname in ('builtins.True', 'builtins.False'):
  371. return ModelConfigData(**{lhs.name: substmt.rvalue.fullname == 'builtins.True'})
  372. error_invalid_config_value(lhs.name, self._ctx.api, substmt)
  373. return None
  374. @staticmethod
  375. def get_is_required(cls: ClassDef, stmt: AssignmentStmt, lhs: NameExpr) -> bool:
  376. """
  377. Returns a boolean indicating whether the field defined in `stmt` is a required field.
  378. """
  379. expr = stmt.rvalue
  380. if isinstance(expr, TempNode):
  381. # TempNode means annotation-only, so only non-required if Optional
  382. value_type = get_proper_type(cls.info[lhs.name].type)
  383. if isinstance(value_type, UnionType) and any(isinstance(item, NoneType) for item in value_type.items):
  384. # Annotated as Optional, or otherwise having NoneType in the union
  385. return False
  386. return True
  387. if isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME:
  388. # The "default value" is a call to `Field`; at this point, the field is
  389. # only required if default is Ellipsis (i.e., `field_name: Annotation = Field(...)`)
  390. return len(expr.args) > 0 and expr.args[0].__class__ is EllipsisExpr
  391. # Only required if the "default value" is Ellipsis (i.e., `field_name: Annotation = ...`)
  392. return isinstance(expr, EllipsisExpr)
  393. @staticmethod
  394. def get_alias_info(stmt: AssignmentStmt) -> Tuple[Optional[str], bool]:
  395. """
  396. Returns a pair (alias, has_dynamic_alias), extracted from the declaration of the field defined in `stmt`.
  397. `has_dynamic_alias` is True if and only if an alias is provided, but not as a string literal.
  398. If `has_dynamic_alias` is True, `alias` will be None.
  399. """
  400. expr = stmt.rvalue
  401. if isinstance(expr, TempNode):
  402. # TempNode means annotation-only
  403. return None, False
  404. if not (
  405. isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME
  406. ):
  407. # Assigned value is not a call to pydantic.fields.Field
  408. return None, False
  409. for i, arg_name in enumerate(expr.arg_names):
  410. if arg_name != 'alias':
  411. continue
  412. arg = expr.args[i]
  413. if isinstance(arg, StrExpr):
  414. return arg.value, False
  415. else:
  416. return None, True
  417. return None, False
  418. def get_field_arguments(
  419. self, fields: List['PydanticModelField'], typed: bool, force_all_optional: bool, use_alias: bool
  420. ) -> List[Argument]:
  421. """
  422. Helper function used during the construction of the `__init__` and `construct` method signatures.
  423. Returns a list of mypy Argument instances for use in the generated signatures.
  424. """
  425. info = self._ctx.cls.info
  426. arguments = [
  427. field.to_argument(info, typed=typed, force_optional=force_all_optional, use_alias=use_alias)
  428. for field in fields
  429. if not (use_alias and field.has_dynamic_alias)
  430. ]
  431. return arguments
  432. def should_init_forbid_extra(self, fields: List['PydanticModelField'], config: 'ModelConfigData') -> bool:
  433. """
  434. Indicates whether the generated `__init__` should get a `**kwargs` at the end of its signature
  435. We disallow arbitrary kwargs if the extra config setting is "forbid", or if the plugin config says to,
  436. *unless* a required dynamic alias is present (since then we can't determine a valid signature).
  437. """
  438. if not config.allow_population_by_field_name:
  439. if self.is_dynamic_alias_present(fields, bool(config.has_alias_generator)):
  440. return False
  441. if config.forbid_extra:
  442. return True
  443. return self.plugin_config.init_forbid_extra
  444. @staticmethod
  445. def is_dynamic_alias_present(fields: List['PydanticModelField'], has_alias_generator: bool) -> bool:
  446. """
  447. Returns whether any fields on the model have a "dynamic alias", i.e., an alias that cannot be
  448. determined during static analysis.
  449. """
  450. for field in fields:
  451. if field.has_dynamic_alias:
  452. return True
  453. if has_alias_generator:
  454. for field in fields:
  455. if field.alias is None:
  456. return True
  457. return False
  458. class PydanticModelField:
  459. def __init__(
  460. self, name: str, is_required: bool, alias: Optional[str], has_dynamic_alias: bool, line: int, column: int
  461. ):
  462. self.name = name
  463. self.is_required = is_required
  464. self.alias = alias
  465. self.has_dynamic_alias = has_dynamic_alias
  466. self.line = line
  467. self.column = column
  468. def to_var(self, info: TypeInfo, use_alias: bool) -> Var:
  469. name = self.name
  470. if use_alias and self.alias is not None:
  471. name = self.alias
  472. return Var(name, info[self.name].type)
  473. def to_argument(self, info: TypeInfo, typed: bool, force_optional: bool, use_alias: bool) -> Argument:
  474. if typed and info[self.name].type is not None:
  475. type_annotation = info[self.name].type
  476. else:
  477. type_annotation = AnyType(TypeOfAny.explicit)
  478. return Argument(
  479. variable=self.to_var(info, use_alias),
  480. type_annotation=type_annotation,
  481. initializer=None,
  482. kind=ARG_NAMED_OPT if force_optional or not self.is_required else ARG_NAMED,
  483. )
  484. def serialize(self) -> JsonDict:
  485. return self.__dict__
  486. @classmethod
  487. def deserialize(cls, info: TypeInfo, data: JsonDict) -> 'PydanticModelField':
  488. return cls(**data)
  489. class ModelConfigData:
  490. def __init__(
  491. self,
  492. forbid_extra: Optional[bool] = None,
  493. allow_mutation: Optional[bool] = None,
  494. frozen: Optional[bool] = None,
  495. orm_mode: Optional[bool] = None,
  496. allow_population_by_field_name: Optional[bool] = None,
  497. has_alias_generator: Optional[bool] = None,
  498. ):
  499. self.forbid_extra = forbid_extra
  500. self.allow_mutation = allow_mutation
  501. self.frozen = frozen
  502. self.orm_mode = orm_mode
  503. self.allow_population_by_field_name = allow_population_by_field_name
  504. self.has_alias_generator = has_alias_generator
  505. def set_values_dict(self) -> Dict[str, Any]:
  506. return {k: v for k, v in self.__dict__.items() if v is not None}
  507. def update(self, config: Optional['ModelConfigData']) -> None:
  508. if config is None:
  509. return
  510. for k, v in config.set_values_dict().items():
  511. setattr(self, k, v)
  512. def setdefault(self, key: str, value: Any) -> None:
  513. if getattr(self, key) is None:
  514. setattr(self, key, value)
  515. ERROR_ORM = ErrorCode('pydantic-orm', 'Invalid from_orm call', 'Pydantic')
  516. ERROR_CONFIG = ErrorCode('pydantic-config', 'Invalid config value', 'Pydantic')
  517. ERROR_ALIAS = ErrorCode('pydantic-alias', 'Dynamic alias disallowed', 'Pydantic')
  518. ERROR_UNEXPECTED = ErrorCode('pydantic-unexpected', 'Unexpected behavior', 'Pydantic')
  519. ERROR_UNTYPED = ErrorCode('pydantic-field', 'Untyped field disallowed', 'Pydantic')
  520. def error_from_orm(model_name: str, api: CheckerPluginInterface, context: Context) -> None:
  521. api.fail(f'"{model_name}" does not have orm_mode=True', context, code=ERROR_ORM)
  522. def error_invalid_config_value(name: str, api: SemanticAnalyzerPluginInterface, context: Context) -> None:
  523. api.fail(f'Invalid value for "Config.{name}"', context, code=ERROR_CONFIG)
  524. def error_required_dynamic_aliases(api: SemanticAnalyzerPluginInterface, context: Context) -> None:
  525. api.fail('Required dynamic aliases disallowed', context, code=ERROR_ALIAS)
  526. def error_unexpected_behavior(detail: str, api: CheckerPluginInterface, context: Context) -> None: # pragma: no cover
  527. # Can't think of a good way to test this, but I confirmed it renders as desired by adding to a non-error path
  528. link = 'https://github.com/samuelcolvin/pydantic/issues/new/choose'
  529. full_message = f'The pydantic mypy plugin ran into unexpected behavior: {detail}\n'
  530. full_message += f'Please consider reporting this bug at {link} so we can try to fix it!'
  531. api.fail(full_message, context, code=ERROR_UNEXPECTED)
  532. def error_untyped_fields(api: SemanticAnalyzerPluginInterface, context: Context) -> None:
  533. api.fail('Untyped fields disallowed', context, code=ERROR_UNTYPED)
  534. def add_method(
  535. ctx: ClassDefContext,
  536. name: str,
  537. args: List[Argument],
  538. return_type: Type,
  539. self_type: Optional[Type] = None,
  540. tvar_def: Optional[TypeVarDef] = None,
  541. is_classmethod: bool = False,
  542. is_new: bool = False,
  543. # is_staticmethod: bool = False,
  544. ) -> None:
  545. """
  546. Adds a new method to a class.
  547. This can be dropped if/when https://github.com/python/mypy/issues/7301 is merged
  548. """
  549. info = ctx.cls.info
  550. # First remove any previously generated methods with the same name
  551. # to avoid clashes and problems in the semantic analyzer.
  552. if name in info.names:
  553. sym = info.names[name]
  554. if sym.plugin_generated and isinstance(sym.node, FuncDef):
  555. ctx.cls.defs.body.remove(sym.node)
  556. self_type = self_type or fill_typevars(info)
  557. if is_classmethod or is_new:
  558. first = [Argument(Var('_cls'), TypeType.make_normalized(self_type), None, ARG_POS)]
  559. # elif is_staticmethod:
  560. # first = []
  561. else:
  562. self_type = self_type or fill_typevars(info)
  563. first = [Argument(Var('__pydantic_self__'), self_type, None, ARG_POS)]
  564. args = first + args
  565. arg_types, arg_names, arg_kinds = [], [], []
  566. for arg in args:
  567. assert arg.type_annotation, 'All arguments must be fully typed.'
  568. arg_types.append(arg.type_annotation)
  569. arg_names.append(get_name(arg.variable))
  570. arg_kinds.append(arg.kind)
  571. function_type = ctx.api.named_type(f'{BUILTINS_NAME}.function')
  572. signature = CallableType(arg_types, arg_kinds, arg_names, return_type, function_type)
  573. if tvar_def:
  574. signature.variables = [tvar_def]
  575. func = FuncDef(name, args, Block([PassStmt()]))
  576. func.info = info
  577. func.type = set_callable_name(signature, func)
  578. func.is_class = is_classmethod
  579. # func.is_static = is_staticmethod
  580. func._fullname = get_fullname(info) + '.' + name
  581. func.line = info.line
  582. # NOTE: we would like the plugin generated node to dominate, but we still
  583. # need to keep any existing definitions so they get semantically analyzed.
  584. if name in info.names:
  585. # Get a nice unique name instead.
  586. r_name = get_unique_redefinition_name(name, info.names)
  587. info.names[r_name] = info.names[name]
  588. if is_classmethod: # or is_staticmethod:
  589. func.is_decorated = True
  590. v = Var(name, func.type)
  591. v.info = info
  592. v._fullname = func._fullname
  593. # if is_classmethod:
  594. v.is_classmethod = True
  595. dec = Decorator(func, [NameExpr('classmethod')], v)
  596. # else:
  597. # v.is_staticmethod = True
  598. # dec = Decorator(func, [NameExpr('staticmethod')], v)
  599. dec.line = info.line
  600. sym = SymbolTableNode(MDEF, dec)
  601. else:
  602. sym = SymbolTableNode(MDEF, func)
  603. sym.plugin_generated = True
  604. info.names[name] = sym
  605. info.defn.defs.body.append(func)
  606. def get_fullname(x: Union[FuncBase, SymbolNode]) -> str:
  607. """
  608. Used for compatibility with mypy 0.740; can be dropped once support for 0.740 is dropped.
  609. """
  610. fn = x.fullname
  611. if callable(fn): # pragma: no cover
  612. return fn()
  613. return fn
  614. def get_name(x: Union[FuncBase, SymbolNode]) -> str:
  615. """
  616. Used for compatibility with mypy 0.740; can be dropped once support for 0.740 is dropped.
  617. """
  618. fn = x.name
  619. if callable(fn): # pragma: no cover
  620. return fn()
  621. return fn
  622. def parse_toml(config_file: str) -> Optional[Dict[str, Any]]:
  623. if not config_file.endswith('.toml'):
  624. return None
  625. read_mode = 'rb'
  626. try:
  627. import tomli as toml_
  628. except ImportError:
  629. # older versions of mypy have toml as a dependency, not tomli
  630. read_mode = 'r'
  631. try:
  632. import toml as toml_ # type: ignore[no-redef]
  633. except ImportError: # pragma: no cover
  634. import warnings
  635. warnings.warn('No TOML parser installed, cannot read configuration from `pyproject.toml`.')
  636. return None
  637. with open(config_file, read_mode) as rf:
  638. return toml_.load(rf) # type: ignore[arg-type]