mypy.py 38 KB

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