Coverage for pydantic / mypy.py: 90.75%

631 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-21 11:56 +0000

1"""This module includes classes and functions designed specifically for use with the mypy plugin.""" 

2 

3from __future__ import annotations 1bcdefghijklmanopqrs

4 

5import sys 1bcdefghijklmanopqrs

6import tomllib 1bcdefghijklmanopqrs

7from collections.abc import Callable, Iterator 1bcdefghijklmanopqrs

8from configparser import ConfigParser 1bcdefghijklmanopqrs

9from typing import Any 1bcdefghijklmanopqrs

10 

11# To avoid import error (https://github.com/python/mypy/issues/17726): 

12import mypy.types # noqa: F401 1bcdefghijklmanopqrs

13from mypy.errorcodes import ErrorCode 1a

14from mypy.expandtype import expand_type, expand_type_by_instance 1a

15from mypy.nodes import ( 1a

16 ARG_NAMED, 

17 ARG_NAMED_OPT, 

18 ARG_OPT, 

19 ARG_POS, 

20 ARG_STAR2, 

21 GDEF, 

22 INVARIANT, 

23 MDEF, 

24 Argument, 

25 AssignmentStmt, 

26 Block, 

27 CallExpr, 

28 ClassDef, 

29 Context, 

30 Decorator, 

31 DictExpr, 

32 EllipsisExpr, 

33 Expression, 

34 FuncDef, 

35 IfStmt, 

36 JsonDict, 

37 NameExpr, 

38 PassStmt, 

39 PlaceholderNode, 

40 RefExpr, 

41 Statement, 

42 StrExpr, 

43 SymbolTableNode, 

44 TempNode, 

45 TypeAlias, 

46 TypeInfo, 

47 Var, 

48) 

49from mypy.options import Options 1a

50from mypy.plugin import ( 1a

51 CheckerPluginInterface, 

52 ClassDefContext, 

53 DynamicClassDefContext, 

54 Plugin, 

55 ReportConfigContext, 

56 SemanticAnalyzerPluginInterface, 

57) 

58from mypy.plugins.common import ( 1a

59 deserialize_and_fixup_type, 

60) 

61from mypy.semanal import set_callable_name 1a

62from mypy.semanal_shared import has_placeholder 1a

63from mypy.server.trigger import make_wildcard_trigger 1a

64from mypy.state import state 1a

65from mypy.type_visitor import TypeTranslator 1a

66from mypy.typeops import map_type_from_supertype 1a

67from mypy.types import ( 1a

68 AnyType, 

69 CallableType, 

70 Instance, 

71 NoneType, 

72 Type, 

73 TypeOfAny, 

74 TypeType, 

75 TypeVarType, 

76 UnionType, 

77 get_proper_type, 

78) 

79from mypy.typevars import fill_typevars 1a

80from mypy.util import get_unique_redefinition_name 1a

81from mypy.version import __version__ as mypy_version 1a

82 

83from pydantic._internal import _fields 1a

84from pydantic.version import parse_mypy_version 1a

85 

86CONFIGFILE_KEY = 'pydantic-mypy' 1a

87METADATA_KEY = 'pydantic-mypy-metadata' 1a

88METADATA_TAG_KEY = 'pydantic-mypy-metadata-tag' 1a

89BASEMODEL_FULLNAME = 'pydantic.main.BaseModel' 1a

90CREATE_MODEL_FULLNAME = 'pydantic.main.create_model' 1a

91BASESETTINGS_FULLNAME = 'pydantic_settings.main.BaseSettings' 1a

92ROOT_MODEL_FULLNAME = 'pydantic.root_model.RootModel' 1a

93MODEL_METACLASS_FULLNAME = 'pydantic._internal._model_construction.ModelMetaclass' 1a

94ROOT_MODEL_METACLASS_FULLNAME = 'pydantic.root_model._RootModelMetaclass' 1a

95FIELD_FULLNAME = 'pydantic.fields.Field' 1a

96DATACLASS_FULLNAME = 'pydantic.dataclasses.dataclass' 1a

97MODEL_VALIDATOR_FULLNAME = 'pydantic.functional_validators.model_validator' 1a

98DECORATOR_FULLNAMES = { 1a

99 'pydantic.functional_validators.field_validator', 

100 'pydantic.functional_validators.model_validator', 

101 'pydantic.functional_serializers.serializer', 

102 'pydantic.functional_serializers.model_serializer', 

103} 

104IMPLICIT_CLASSMETHOD_DECORATOR_FULLNAMES = DECORATOR_FULLNAMES - {'pydantic.functional_serializers.model_serializer'} 1a

105 

106 

107MYPY_VERSION_TUPLE = parse_mypy_version(mypy_version) 1a

108BUILTINS_NAME = 'builtins' 1a

109 

110# Increment version if plugin changes and mypy caches should be invalidated 

111__version__ = 2 1a

112 

113 

114def plugin(version: str) -> type[Plugin]: 1a

115 """`version` is the mypy version string. 

116 

117 We might want to use this to print a warning if the mypy version being used is 

118 newer, or especially older, than we expect (or need). 

119 

120 Args: 

121 version: The mypy version string. 

122 

123 Return: 

124 The Pydantic mypy plugin type. 

125 """ 

126 return PydanticPlugin 1a

127 

128 

129class PydanticPlugin(Plugin): 1a

130 """The Pydantic mypy plugin.""" 

131 

132 def __init__(self, options: Options) -> None: 1a

133 self.plugin_config = PydanticPluginConfig(options) 1a

134 self._plugin_data = self.plugin_config.to_data() 1a

135 super().__init__(options) 1a

136 

137 def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: 1a

138 """Update Pydantic model class.""" 

139 sym = self.lookup_fully_qualified(fullname) 1a

140 if sym and isinstance(sym.node, TypeInfo): # pragma: no branch 1a

141 # No branching may occur if the mypy cache has not been cleared 

142 if sym.node.has_base(BASEMODEL_FULLNAME): 1a

143 return self._pydantic_model_class_maker_callback 1a

144 return None 1a

145 

146 def get_metaclass_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: 1a

147 """Update Pydantic `ModelMetaclass` definition.""" 

148 if fullname in (MODEL_METACLASS_FULLNAME, ROOT_MODEL_METACLASS_FULLNAME): 1a

149 return self._pydantic_model_metaclass_marker_callback 1a

150 return None 1a

151 

152 def get_dynamic_class_hook(self, fullname: str) -> Callable[[DynamicClassDefContext], None] | None: 1a

153 """Recognize `create_model()` calls as dynamic BaseModel subclasses.""" 

154 if fullname == CREATE_MODEL_FULLNAME: 1a

155 return self._pydantic_create_model_callback 1a

156 return None 1a

157 

158 def report_config_data(self, ctx: ReportConfigContext) -> dict[str, Any]: 1a

159 """Return all plugin config data. 

160 

161 Used by mypy to determine if cache needs to be discarded. 

162 """ 

163 return self._plugin_data 1a

164 

165 def _pydantic_model_class_maker_callback(self, ctx: ClassDefContext) -> None: 1a

166 transformer = PydanticModelTransformer(ctx.cls, ctx.reason, ctx.api, self.plugin_config) 1a

167 transformer.transform() 1a

168 

169 def _pydantic_model_metaclass_marker_callback(self, ctx: ClassDefContext) -> None: 1a

170 """Reset dataclass_transform_spec attribute of ModelMetaclass. 

171 

172 Let the plugin handle it. This behavior can be disabled 

173 if 'debug_dataclass_transform' is set to True', for testing purposes. 

174 """ 

175 if self.plugin_config.debug_dataclass_transform: 175 ↛ 176line 175 didn't jump to line 176 because the condition on line 175 was never true1a

176 return 

177 info_metaclass = ctx.cls.info.declared_metaclass 1a

178 assert info_metaclass, "callback not passed from 'get_metaclass_hook'" 1a

179 if getattr(info_metaclass.type, 'dataclass_transform_spec', None): 1a

180 info_metaclass.type.dataclass_transform_spec = None 1a

181 

182 def _pydantic_create_model_callback(self, ctx: DynamicClassDefContext) -> None: 1a

183 """Make variables assigned from `create_model()` usable as types by mypy.""" 

184 # Determine the base class from __base__ argument if provided 

185 base_fullname = BASEMODEL_FULLNAME 1a

186 for arg_name, arg_expr in zip(ctx.call.arg_names, ctx.call.args, strict=True): 1a

187 if arg_name == '__base__' and isinstance(arg_expr, RefExpr) and arg_expr.node is not None: 1a

188 if isinstance(arg_expr.node, TypeInfo): 1a

189 base_fullname = arg_expr.node.fullname 1a

190 elif isinstance(arg_expr.node, Var): 190 ↛ 186line 190 didn't jump to line 186 because the condition on line 190 was always true1a

191 arg_type = get_proper_type(arg_expr.node.type) 1a

192 if isinstance(arg_type, Instance): 192 ↛ 193line 192 didn't jump to line 193 because the condition on line 192 was never true1a

193 base_fullname = arg_type.type.fullname 

194 elif isinstance(arg_type, TypeType): 194 ↛ 186line 194 didn't jump to line 186 because the condition on line 194 was always true1a

195 item_type = get_proper_type(arg_type.item) 1a

196 if isinstance(item_type, TypeVarType): 196 ↛ 201line 196 didn't jump to line 201 because the condition on line 196 was always true1a

197 # Inside classmethods, `cls` is modeled as `type[Self]`. Creating a concrete 

198 # synthetic type here loses that type variable, so let mypy use infer the correct type 

199 # from the `create_model()` overload with the type var instead. 

200 return 1a

201 if isinstance(item_type, Instance): 

202 base_fullname = item_type.type.fullname 

203 

204 base_sym = ctx.api.lookup_fully_qualified_or_none(base_fullname) 1a

205 if base_sym is None or not isinstance(base_sym.node, TypeInfo): 205 ↛ 207line 205 didn't jump to line 207 because the condition on line 205 was never true1a

206 # Fall back to BaseModel 

207 base_sym = ctx.api.lookup_fully_qualified_or_none(BASEMODEL_FULLNAME) 

208 if base_sym is None or not isinstance(base_sym.node, TypeInfo): 

209 return 

210 

211 base_info = base_sym.node 1a

212 base_instance = fill_typevars(base_info) 1a

213 assert isinstance(base_instance, Instance) 1a

214 

215 info = ctx.api.basic_new_typeinfo(ctx.name, base_instance, ctx.call.line) 1a

216 info.metaclass_type = base_info.metaclass_type 1a

217 

218 ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(MDEF, info)) 1a

219 

220 # Mypy has a quirk for serialization of classes nested in functions. This is 

221 # a workaround that should work in most cases, until mypy has a better plugin API. 

222 if '@' in info.fullname: 1a

223 _, name = info.fullname.rsplit('.', maxsplit=1) 1a

224 ctx.api.modules[ctx.api.cur_mod_id].names[name] = SymbolTableNode(GDEF, info) 1a

225 

226 

227class PydanticPluginConfig: 1a

228 """A Pydantic mypy plugin config holder. 

229 

230 Attributes: 

231 init_forbid_extra: Whether to add a `**kwargs` at the end of the generated `__init__` signature. 

232 init_typed: Whether to annotate fields in the generated `__init__`. 

233 warn_required_dynamic_aliases: Whether to raise required dynamic aliases error. 

234 debug_dataclass_transform: Whether to not reset `dataclass_transform_spec` attribute 

235 of `ModelMetaclass` for testing purposes. 

236 """ 

237 

238 __slots__ = ( 1a

239 'init_forbid_extra', 

240 'init_typed', 

241 'warn_required_dynamic_aliases', 

242 'debug_dataclass_transform', 

243 ) 

244 init_forbid_extra: bool 1a

245 init_typed: bool 1a

246 warn_required_dynamic_aliases: bool 1a

247 debug_dataclass_transform: bool # undocumented 1a

248 

249 def __init__(self, options: Options) -> None: 1a

250 if options.config_file is None: # pragma: no cover 1a

251 return 

252 

253 toml_config = parse_toml(options.config_file) 1a

254 if toml_config is not None: 1a

255 config = toml_config.get('tool', {}).get('pydantic-mypy', {}) 1a

256 for key in self.__slots__: 1a

257 setting = config.get(key, False) 1a

258 if not isinstance(setting, bool): 1a

259 raise ValueError(f'Configuration value must be a boolean for key: {key}') 1a

260 setattr(self, key, setting) 1a

261 unknown_keys = config.keys() - set(self.__slots__) 1a

262 for key in sorted(unknown_keys): 1a

263 print(f'[pydantic-mypy]: Unrecognized option: {key} = {config[key]}', file=sys.stderr) # noqa: T201 1a

264 else: 

265 plugin_config = ConfigParser() 1a

266 plugin_config.read(options.config_file) 1a

267 for key in self.__slots__: 1a

268 setting = plugin_config.getboolean(CONFIGFILE_KEY, key, fallback=False) 1a

269 setattr(self, key, setting) 1a

270 if plugin_config.has_section(CONFIGFILE_KEY): 1a

271 unknown_keys = set(plugin_config.options(CONFIGFILE_KEY)) - set(self.__slots__) 1a

272 for key in sorted(unknown_keys): 1a

273 print( # noqa: T201 1a

274 f'[pydantic-mypy]: Unrecognized option: {key} = {plugin_config.get(CONFIGFILE_KEY, key)}', 

275 file=sys.stderr, 

276 ) 

277 

278 def to_data(self) -> dict[str, Any]: 1a

279 """Returns a dict of config names to their values.""" 

280 return {key: getattr(self, key) for key in self.__slots__} 1a

281 

282 

283class PydanticModelField: 1a

284 """Based on mypy.plugins.dataclasses.DataclassAttribute.""" 

285 

286 def __init__( 1a

287 self, 

288 name: str, 

289 alias: str | None, 

290 is_frozen: bool, 

291 has_dynamic_alias: bool, 

292 has_default: bool, 

293 strict: bool | None, 

294 line: int, 

295 column: int, 

296 type: Type | None, 

297 info: TypeInfo, 

298 ): 

299 self.name = name 1a

300 self.alias = alias 1a

301 self.is_frozen = is_frozen 1a

302 self.has_dynamic_alias = has_dynamic_alias 1a

303 self.has_default = has_default 1a

304 self.strict = strict 1a

305 self.line = line 1a

306 self.column = column 1a

307 self.type = type 1a

308 self.info = info 1a

309 

310 def to_argument( 1a

311 self, 

312 current_info: TypeInfo, 

313 typed: bool, 

314 model_strict: bool, 

315 force_optional: bool, 

316 use_alias: bool, 

317 api: SemanticAnalyzerPluginInterface, 

318 force_typevars_invariant: bool, 

319 is_root_model_root: bool, 

320 ) -> Argument: 

321 """Based on mypy.plugins.dataclasses.DataclassAttribute.to_argument.""" 

322 variable = self.to_var(current_info, api, use_alias, force_typevars_invariant) 1a

323 

324 strict = model_strict if self.strict is None else self.strict 1a

325 if typed or strict: 1a

326 type_annotation = self.expand_type(current_info, api, include_root_type=True) 1a

327 else: 

328 type_annotation = AnyType(TypeOfAny.special_form) 1a

329 

330 return Argument( 1a

331 variable=variable, 

332 type_annotation=type_annotation, 

333 initializer=None, 

334 kind=ARG_OPT 

335 if is_root_model_root 

336 else (ARG_NAMED_OPT if force_optional or self.has_default else ARG_NAMED), 

337 ) 

338 

339 def expand_type( 1a

340 self, 

341 current_info: TypeInfo, 

342 api: SemanticAnalyzerPluginInterface, 

343 force_typevars_invariant: bool = False, 

344 include_root_type: bool = False, 

345 ) -> Type | None: 

346 """Based on mypy.plugins.dataclasses.DataclassAttribute.expand_type.""" 

347 if force_typevars_invariant: 1a

348 # In some cases, mypy will emit an error "Cannot use a covariant type variable as a parameter" 

349 # To prevent that, we add an option to replace typevars with invariant ones while building certain 

350 # method signatures (in particular, `__init__`). There may be a better way to do this, if this causes 

351 # us problems in the future, we should look into why the dataclasses plugin doesn't have this issue. 

352 if isinstance(self.type, TypeVarType): 1a

353 modified_type = self.type.copy_modified() 1a

354 modified_type.variance = INVARIANT 1a

355 self.type = modified_type 1a

356 

357 if self.type is not None and self.info.self_type is not None: 357 ↛ 382line 357 didn't jump to line 382 because the condition on line 357 was always true1a

358 # In general, it is not safe to call `expand_type()` during semantic analysis, 

359 # however this plugin is called very late, so all types should be fully ready. 

360 # Also, it is tricky to avoid eager expansion of Self types here (e.g. because 

361 # we serialize attributes). 

362 with state.strict_optional_set(api.options.strict_optional): 1a

363 filled_with_typevars = fill_typevars(current_info) 1a

364 # Cannot be TupleType as current_info represents a Pydantic model: 

365 assert isinstance(filled_with_typevars, Instance) 1a

366 if force_typevars_invariant: 1a

367 for arg in filled_with_typevars.args: 1a

368 if isinstance(arg, TypeVarType): 368 ↛ 367line 368 didn't jump to line 367 because the condition on line 368 was always true1a

369 arg.variance = INVARIANT 1a

370 

371 expanded_type = expand_type(self.type, {self.info.self_type.id: filled_with_typevars}) 1a

372 if include_root_type and isinstance(expanded_type, Instance) and is_root_model(expanded_type.type): 1a

373 # When a root model is used as a field, Pydantic allows both an instance of the root model 

374 # as well as instances of the `root` field type: 

375 root_type = expanded_type.type['root'].type 1a

376 if root_type is None: 376 ↛ 378line 376 didn't jump to line 378 because the condition on line 376 was never true1a

377 # Happens if the hint for 'root' has unsolved forward references 

378 return expanded_type 

379 expanded_root_type = expand_type_by_instance(root_type, expanded_type) 1a

380 expanded_type = UnionType([expanded_type, expanded_root_type]) 1a

381 return expanded_type 1a

382 return self.type 

383 

384 def to_var( 1a

385 self, 

386 current_info: TypeInfo, 

387 api: SemanticAnalyzerPluginInterface, 

388 use_alias: bool, 

389 force_typevars_invariant: bool = False, 

390 ) -> Var: 

391 """Based on mypy.plugins.dataclasses.DataclassAttribute.to_var.""" 

392 if use_alias and self.alias is not None: 1a

393 name = self.alias 1a

394 else: 

395 name = self.name 1a

396 

397 return Var(name, self.expand_type(current_info, api, force_typevars_invariant)) 1a

398 

399 def serialize(self) -> JsonDict: 1a

400 """Based on mypy.plugins.dataclasses.DataclassAttribute.serialize.""" 

401 assert self.type 1a

402 return { 1a

403 'name': self.name, 

404 'alias': self.alias, 

405 'is_frozen': self.is_frozen, 

406 'has_dynamic_alias': self.has_dynamic_alias, 

407 'has_default': self.has_default, 

408 'strict': self.strict, 

409 'line': self.line, 

410 'column': self.column, 

411 'type': self.type.serialize(), 

412 } 

413 

414 @classmethod 1a

415 def deserialize(cls, info: TypeInfo, data: JsonDict, api: SemanticAnalyzerPluginInterface) -> PydanticModelField: 1a

416 """Based on mypy.plugins.dataclasses.DataclassAttribute.deserialize.""" 

417 data = data.copy() 1a

418 typ = deserialize_and_fixup_type(data.pop('type'), api) 1a

419 return cls(type=typ, info=info, **data) 1a

420 

421 def expand_typevar_from_subtype(self, sub_type: TypeInfo, api: SemanticAnalyzerPluginInterface) -> None: 1a

422 """Expands type vars in the context of a subtype when an attribute is inherited 

423 from a generic super type. 

424 """ 

425 if self.type is not None: 425 ↛ exitline 425 didn't return from function 'expand_typevar_from_subtype' because the condition on line 425 was always true1a

426 with state.strict_optional_set(api.options.strict_optional): 1a

427 self.type = map_type_from_supertype(self.type, sub_type, self.info) 1a

428 

429 

430class PydanticModelClassVar: 1a

431 """Based on mypy.plugins.dataclasses.DataclassAttribute. 

432 

433 ClassVars are ignored by subclasses. 

434 

435 Attributes: 

436 name: the ClassVar name 

437 """ 

438 

439 def __init__(self, name): 1a

440 self.name = name 1a

441 

442 @classmethod 1a

443 def deserialize(cls, data: JsonDict) -> PydanticModelClassVar: 1a

444 """Based on mypy.plugins.dataclasses.DataclassAttribute.deserialize.""" 

445 data = data.copy() 

446 return cls(**data) 

447 

448 def serialize(self) -> JsonDict: 1a

449 """Based on mypy.plugins.dataclasses.DataclassAttribute.serialize.""" 

450 return { 1a

451 'name': self.name, 

452 } 

453 

454 

455class PydanticModelTransformer: 1a

456 """Transform the BaseModel subclass according to the plugin settings. 

457 

458 Attributes: 

459 tracked_config_fields: A set of field configs that the plugin has to track their value. 

460 """ 

461 

462 tracked_config_fields: set[str] = { 1a

463 'extra', 

464 'frozen', 

465 'populate_by_name', 

466 'validate_by_alias', 

467 'validate_by_name', 

468 'alias_generator', 

469 'strict', 

470 } 

471 

472 def __init__( 1a

473 self, 

474 cls: ClassDef, 

475 reason: Expression | Statement, 

476 api: SemanticAnalyzerPluginInterface, 

477 plugin_config: PydanticPluginConfig, 

478 ) -> None: 

479 self._cls = cls 1a

480 self._reason = reason 1a

481 self._api = api 1a

482 

483 self.plugin_config = plugin_config 1a

484 

485 def transform(self) -> bool: 1a

486 """Configures the BaseModel subclass according to the plugin settings. 

487 

488 In particular: 

489 

490 * determines the model config and fields, 

491 * adds a fields-aware signature for the initializer and construct methods 

492 * freezes the class if frozen = True 

493 * stores the fields, config, and if the class is settings in the mypy metadata for access by subclasses 

494 """ 

495 info = self._cls.info 1a

496 # Tag the class as being processed by the plugin. This is used to detect base classes 

497 # that are Pydantic models for which the plugin hasn't completed processing yet (in which 

498 # case the `METADATA_KEY` is not yet present in the metadata): 

499 info.metadata.setdefault(METADATA_TAG_KEY, {}) 1a

500 is_a_root_model = is_root_model(info) 1a

501 config = self.collect_config() 1a

502 fields, class_vars = self.collect_fields_and_class_vars(config, is_a_root_model) 1a

503 if fields is None or class_vars is None: 1a

504 # Some definitions are not ready. We need another pass. 

505 if not self._api.final_iteration: 505 ↛ 507line 505 didn't jump to line 507 because the condition on line 505 was always true1a

506 self._api.defer() 1a

507 return False 1a

508 for field in fields: 1a

509 if field.type is None or has_placeholder(field.type): 1a

510 # The field type may contain placeholders, e.g. when inheriting from a generic 

511 # model parametrized with a forward reference to the class being defined. 

512 # Request another pass so that they can be resolved: 

513 if not self._api.final_iteration: 513 ↛ 515line 513 didn't jump to line 515 because the condition on line 513 was always true1a

514 self._api.defer() 1a

515 return False 1a

516 for tv in info.defn.type_vars: 1a

517 if has_placeholder(tv) and not self._api.final_iteration: 1a

518 self._api.defer() 1a

519 return False 1a

520 

521 is_settings = info.has_base(BASESETTINGS_FULLNAME) 1a

522 self.add_initializer(fields, config, is_settings, is_a_root_model) 1a

523 self.add_model_construct_method(fields, config, is_settings, is_a_root_model) 1a

524 self.set_frozen(fields, self._api, frozen=config.frozen is True) 1a

525 

526 self.adjust_decorator_signatures() 1a

527 

528 info.metadata[METADATA_KEY] = { 1a

529 'fields': {field.name: field.serialize() for field in fields}, 

530 'class_vars': {class_var.name: class_var.serialize() for class_var in class_vars}, 

531 'config': config.get_values_dict(), 

532 } 

533 

534 return True 1a

535 

536 def adjust_decorator_signatures(self) -> None: 1a

537 """When we decorate a function `f` with `pydantic.field_validator(...)` 

538 or `pydantic.serializer(...)`, mypy sees `f` as a regular method taking a `self` instance, 

539 even though pydantic internally wraps `f` with `classmethod` if necessary. 

540 

541 Teach mypy this by marking any function whose outermost decorator is a 

542 `field_validator()` or `serializer()` call as a `classmethod`. 

543 """ 

544 for sym in self._cls.info.names.values(): 1a

545 if isinstance(sym.node, Decorator): 1a

546 first_dec = sym.node.original_decorators[0] 1a

547 if ( 

548 isinstance(first_dec, CallExpr) 

549 and isinstance(first_dec.callee, NameExpr) 

550 and first_dec.callee.fullname in IMPLICIT_CLASSMETHOD_DECORATOR_FULLNAMES 

551 # @model_validator(mode="after") is an exception, it expects a regular method 

552 and not ( 

553 first_dec.callee.fullname == MODEL_VALIDATOR_FULLNAME 

554 and any( 

555 first_dec.arg_names[i] == 'mode' and isinstance(arg, StrExpr) and arg.value == 'after' 

556 for i, arg in enumerate(first_dec.args) 

557 ) 

558 ) 

559 ): 

560 # TODO: Only do this if the first argument of the decorated function is `cls` 

561 sym.node.func.is_class = True 1a

562 

563 def collect_config(self) -> ModelConfigData: # noqa: C901 (ignore complexity) 1a

564 """Collects the values of the config attributes that are used by the plugin, accounting for parent classes.""" 

565 cls = self._cls 1a

566 config = ModelConfigData() 1a

567 

568 has_config_kwargs = False 1a

569 has_config_from_namespace = False 1a

570 

571 # Handle `class MyModel(BaseModel, <name>=<expr>, ...):` 

572 for name, expr in cls.keywords.items(): 1a

573 config_data = self.get_config_update(name, expr) 1a

574 if config_data: 1a

575 has_config_kwargs = True 1a

576 config.update(config_data) 1a

577 

578 # Handle `model_config` 

579 stmt: Statement | None = None 1a

580 for stmt in cls.defs.body: 1a

581 if not isinstance(stmt, AssignmentStmt): 1a

582 continue 1a

583 

584 lhs = stmt.lvalues[0] 1a

585 if not isinstance(lhs, NameExpr) or lhs.name != 'model_config': 1a

586 continue 1a

587 

588 if isinstance(stmt.rvalue, CallExpr): # calls to `dict` or `ConfigDict` 1a

589 for arg_name, arg in zip(stmt.rvalue.arg_names, stmt.rvalue.args, strict=True): 1a

590 if arg_name is None: 590 ↛ 591line 590 didn't jump to line 591 because the condition on line 590 was never true1a

591 continue 

592 config.update(self.get_config_update(arg_name, arg, lax_extra=True)) 1a

593 elif isinstance(stmt.rvalue, DictExpr): # dict literals 593 ↛ 599line 593 didn't jump to line 599 because the condition on line 593 was always true1a

594 for key_expr, value_expr in stmt.rvalue.items: 1a

595 if not isinstance(key_expr, StrExpr): 595 ↛ 596line 595 didn't jump to line 596 because the condition on line 595 was never true1a

596 continue 

597 config.update(self.get_config_update(key_expr.value, value_expr)) 1a

598 

599 if has_config_kwargs: 599 ↛ 600line 599 didn't jump to line 600 because the condition on line 599 was never true1a

600 self._api.fail( 

601 'Specifying config in two places is ambiguous, use either Config attribute or class kwargs', 

602 cls, 

603 ) 

604 break 

605 

606 has_config_from_namespace = True 1a

607 

608 if has_config_kwargs or has_config_from_namespace: 1a

609 if ( 

610 stmt 

611 and config.has_alias_generator 

612 and not (config.validate_by_name or config.populate_by_name) 

613 and self.plugin_config.warn_required_dynamic_aliases 

614 ): 

615 error_required_dynamic_aliases(self._api, stmt) 1a

616 

617 for info in cls.info.mro[1:]: # 0 is the current class 1a

618 if METADATA_KEY not in info.metadata: 1a

619 continue 1a

620 

621 # Each class depends on the set of fields in its ancestors 

622 self._api.add_plugin_dependency(make_wildcard_trigger(info.fullname)) 1a

623 for name, value in info.metadata[METADATA_KEY]['config'].items(): 1a

624 config.setdefault(name, value) 1a

625 return config 1a

626 

627 def collect_fields_and_class_vars( 1a

628 self, model_config: ModelConfigData, is_root_model: bool 

629 ) -> tuple[list[PydanticModelField] | None, list[PydanticModelClassVar] | None]: 

630 """Collects the fields for the model, accounting for parent classes.""" 

631 cls = self._cls 1a

632 

633 # First, collect fields and ClassVars belonging to any class in the MRO, ignoring duplicates. 

634 # 

635 # We iterate through the MRO in reverse because attrs defined in the parent must appear 

636 # earlier in the attributes list than attrs defined in the child. See: 

637 # https://docs.python.org/3/library/dataclasses.html#inheritance 

638 # 

639 # However, we also want fields defined in the subtype to override ones defined 

640 # in the parent. We can implement this via a dict without disrupting the attr order 

641 # because dicts preserve insertion order in Python 3.7+. 

642 found_fields: dict[str, PydanticModelField] = {} 1a

643 found_class_vars: dict[str, PydanticModelClassVar] = {} 1a

644 for info in reversed(cls.info.mro[1:-1]): # 0 is the current class, -2 is BaseModel, -1 is object 1a

645 if METADATA_KEY not in info.metadata: 1a

646 if METADATA_TAG_KEY in info.metadata and not self._api.final_iteration: 1a

647 # The base class is a Pydantic model, but the plugin hasn't finished processing it yet 

648 # (e.g. because its own processing got deferred, as it has fields with unresolved 

649 # forward references). We need another pass, otherwise the fields of the base 

650 # class would be missing from the generated signatures of this class. 

651 return None, None 1a

652 continue 1a

653 

654 # Each class depends on the set of attributes in its dataclass ancestors. 

655 self._api.add_plugin_dependency(make_wildcard_trigger(info.fullname)) 1a

656 

657 for name, data in info.metadata[METADATA_KEY]['fields'].items(): 1a

658 field = PydanticModelField.deserialize(info, data, self._api) 1a

659 # (The following comment comes directly from the dataclasses plugin) 

660 # TODO: We shouldn't be performing type operations during the main 

661 # semantic analysis pass, since some TypeInfo attributes might 

662 # still be in flux. This should be performed in a later phase. 

663 field.expand_typevar_from_subtype(cls.info, self._api) 1a

664 found_fields[name] = field 1a

665 

666 sym_node = cls.info.names.get(name) 1a

667 if sym_node and sym_node.node and not isinstance(sym_node.node, (Var, PlaceholderNode)): 1a

668 self._api.fail( 1a

669 'BaseModel field may only be overridden by another field', 

670 sym_node.node, 

671 ) 

672 # Collect ClassVars 

673 for name, data in info.metadata[METADATA_KEY]['class_vars'].items(): 673 ↛ 674line 673 didn't jump to line 674 because the loop on line 673 never started1a

674 found_class_vars[name] = PydanticModelClassVar.deserialize(data) 

675 

676 # Second, collect fields and ClassVars belonging to the current class. 

677 current_field_names: set[str] = set() 1a

678 current_class_vars_names: set[str] = set() 1a

679 for stmt in self._get_assignment_statements_from_block(cls.defs): 1a

680 maybe_field = self.collect_field_or_class_var_from_stmt(stmt, model_config, found_class_vars) 1a

681 if maybe_field is None: 1a

682 continue 1a

683 

684 lhs = stmt.lvalues[0] 1a

685 assert isinstance(lhs, NameExpr) # collect_field_or_class_var_from_stmt guarantees this 1a

686 if isinstance(maybe_field, PydanticModelField): 1a

687 if is_root_model and lhs.name != 'root': 1a

688 error_extra_fields_on_root_model(self._api, stmt) 1a

689 else: 

690 current_field_names.add(lhs.name) 1a

691 found_fields[lhs.name] = maybe_field 1a

692 elif isinstance(maybe_field, PydanticModelClassVar): 692 ↛ 679line 692 didn't jump to line 679 because the condition on line 692 was always true1a

693 current_class_vars_names.add(lhs.name) 1a

694 found_class_vars[lhs.name] = maybe_field 1a

695 

696 return list(found_fields.values()), list(found_class_vars.values()) 1a

697 

698 def _get_assignment_statements_from_if_statement(self, stmt: IfStmt) -> Iterator[AssignmentStmt]: 1a

699 for body in stmt.body: 1a

700 if not body.is_unreachable: 700 ↛ 699line 700 didn't jump to line 699 because the condition on line 700 was always true1a

701 yield from self._get_assignment_statements_from_block(body) 1a

702 if stmt.else_body is not None and not stmt.else_body.is_unreachable: 702 ↛ 703line 702 didn't jump to line 703 because the condition on line 702 was never true1a

703 yield from self._get_assignment_statements_from_block(stmt.else_body) 

704 

705 def _get_assignment_statements_from_block(self, block: Block) -> Iterator[AssignmentStmt]: 1a

706 for stmt in block.body: 1a

707 if isinstance(stmt, AssignmentStmt): 1a

708 yield stmt 1a

709 elif isinstance(stmt, IfStmt): 1a

710 yield from self._get_assignment_statements_from_if_statement(stmt) 1a

711 

712 def collect_field_or_class_var_from_stmt( # noqa C901 1a

713 self, stmt: AssignmentStmt, model_config: ModelConfigData, class_vars: dict[str, PydanticModelClassVar] 

714 ) -> PydanticModelField | PydanticModelClassVar | None: 

715 """Get pydantic model field from statement. 

716 

717 Args: 

718 stmt: The statement. 

719 model_config: Configuration settings for the model. 

720 class_vars: ClassVars already known to be defined on the model. 

721 

722 Returns: 

723 A pydantic model field if it could find the field in statement. Otherwise, `None`. 

724 """ 

725 cls = self._cls 1a

726 

727 lhs = stmt.lvalues[0] 1a

728 if not isinstance(lhs, NameExpr) or not _fields.is_valid_field_name(lhs.name) or lhs.name == 'model_config': 1a

729 return None 1a

730 

731 if not stmt.new_syntax: 1a

732 if ( 

733 isinstance(stmt.rvalue, CallExpr) 

734 and isinstance(stmt.rvalue.callee, CallExpr) 

735 and isinstance(stmt.rvalue.callee.callee, NameExpr) 

736 and stmt.rvalue.callee.callee.fullname in DECORATOR_FULLNAMES 

737 ): 

738 # This is a (possibly-reused) validator or serializer, not a field 

739 # In particular, it looks something like: my_validator = validator('my_field')(f) 

740 # Eventually, we may want to attempt to respect model_config['ignored_types'] 

741 return None 1a

742 

743 if lhs.name in class_vars: 743 ↛ 745line 743 didn't jump to line 745 because the condition on line 743 was never true1a

744 # Class vars are not fields and are not required to be annotated 

745 return None 

746 

747 # The assignment does not have an annotation, and it's not anything else we recognize 

748 error_untyped_fields(self._api, stmt) 1a

749 return None 1a

750 

751 lhs = stmt.lvalues[0] 1a

752 if not isinstance(lhs, NameExpr): 752 ↛ 753line 752 didn't jump to line 753 because the condition on line 752 was never true1a

753 return None 

754 

755 if not _fields.is_valid_field_name(lhs.name) or lhs.name == 'model_config': 755 ↛ 756line 755 didn't jump to line 756 because the condition on line 755 was never true1a

756 return None 

757 

758 sym = cls.info.names.get(lhs.name) 1a

759 if sym is None: # pragma: no cover 1a

760 # This is likely due to a star import (see the dataclasses plugin for a more detailed explanation) 

761 # This is the same logic used in the dataclasses plugin 

762 return None 

763 

764 node = sym.node 1a

765 if isinstance(node, PlaceholderNode): # pragma: no cover 1a

766 # See the PlaceholderNode docstring for more detail about how this can occur 

767 # Basically, it is an edge case when dealing with complex import logic 

768 

769 # The dataclasses plugin now asserts this cannot happen, but I'd rather not error if it does.. 

770 return None 

771 

772 if isinstance(node, TypeAlias): 1a

773 self._api.fail( 

774 'Type aliases inside BaseModel definitions are not supported at runtime', 

775 node, 

776 ) 

777 # Skip processing this node. This doesn't match the runtime behaviour, 

778 # but the only alternative would be to modify the SymbolTable, 

779 # and it's a little hairy to do that in a plugin. 

780 return None 

781 

782 if not isinstance(node, Var): # pragma: no cover 1a

783 # Don't know if this edge case still happens with the `is_valid_field` check above 

784 # but better safe than sorry 

785 

786 # The dataclasses plugin now asserts this cannot happen, but I'd rather not error if it does.. 

787 return None 

788 

789 # x: ClassVar[int] is not a field 

790 if node.is_classvar: 1a

791 return PydanticModelClassVar(lhs.name) 1a

792 

793 # x: InitVar[int] is not supported in BaseModel 

794 node_type = get_proper_type(node.type) 1a

795 if isinstance(node_type, Instance) and node_type.type.fullname == 'dataclasses.InitVar': 795 ↛ 796line 795 didn't jump to line 796 because the condition on line 795 was never true1a

796 self._api.fail( 

797 'InitVar is not supported in BaseModel', 

798 node, 

799 ) 

800 

801 has_default = self.get_has_default(stmt) 1a

802 strict = self.get_strict(stmt) 1a

803 

804 if sym.type is None and node.is_final and node.is_inferred: 804 ↛ 812line 804 didn't jump to line 812 because the condition on line 804 was never true1a

805 # This follows the logic from the dataclasses plugin. The following comment is taken verbatim: 

806 # 

807 # This is a special case, assignment like x: Final = 42 is classified 

808 # annotated above, but mypy strips the `Final` turning it into x = 42. 

809 # We do not support inferred types in dataclasses, so we can try inferring 

810 # type for simple literals, and otherwise require an explicit type 

811 # argument for Final[...]. 

812 typ = self._api.analyze_simple_literal_type(stmt.rvalue, is_final=True) 

813 if typ: 

814 node.type = typ 

815 else: 

816 self._api.fail( 

817 'Need type argument for Final[...] with non-literal default in BaseModel', 

818 stmt, 

819 ) 

820 node.type = AnyType(TypeOfAny.from_error) 

821 

822 alias, has_dynamic_alias = self.get_alias_info(stmt) 1a

823 if ( 

824 has_dynamic_alias 

825 and not (model_config.validate_by_name or model_config.populate_by_name) 

826 and self.plugin_config.warn_required_dynamic_aliases 

827 ): 

828 error_required_dynamic_aliases(self._api, stmt) 1a

829 is_frozen = self.is_field_frozen(stmt) 1a

830 

831 init_type = self._infer_dataclass_attr_init_type(sym, lhs.name, stmt) 1a

832 return PydanticModelField( 1a

833 name=lhs.name, 

834 has_dynamic_alias=has_dynamic_alias, 

835 has_default=has_default, 

836 strict=strict, 

837 alias=alias, 

838 is_frozen=is_frozen, 

839 line=stmt.line, 

840 column=stmt.column, 

841 type=init_type, 

842 info=cls.info, 

843 ) 

844 

845 def _infer_dataclass_attr_init_type(self, sym: SymbolTableNode, name: str, context: Context) -> Type | None: 1a

846 """Infer __init__ argument type for an attribute. 

847 

848 In particular, possibly use the signature of __set__. 

849 """ 

850 default = sym.type 1a

851 if sym.implicit: 851 ↛ 852line 851 didn't jump to line 852 because the condition on line 851 was never true1a

852 return default 

853 t = get_proper_type(sym.type) 1a

854 

855 # Perform a simple-minded inference from the signature of __set__, if present. 

856 # We can't use mypy.checkmember here, since this plugin runs before type checking. 

857 # We only support some basic scanerios here, which is hopefully sufficient for 

858 # the vast majority of use cases. 

859 if not isinstance(t, Instance): 1a

860 return default 1a

861 setter = t.type.get('__set__') 1a

862 if setter: 862 ↛ 863line 862 didn't jump to line 863 because the condition on line 862 was never true1a

863 if isinstance(setter.node, FuncDef): 

864 super_info = t.type.get_containing_type_info('__set__') 

865 assert super_info 

866 if setter.type: 

867 setter_type = get_proper_type(map_type_from_supertype(setter.type, t.type, super_info)) 

868 else: 

869 return AnyType(TypeOfAny.unannotated) 

870 if isinstance(setter_type, CallableType) and setter_type.arg_kinds == [ 

871 ARG_POS, 

872 ARG_POS, 

873 ARG_POS, 

874 ]: 

875 return expand_type_by_instance(setter_type.arg_types[2], t) 

876 else: 

877 self._api.fail(f'Unsupported signature for "__set__" in "{t.type.name}"', context) 

878 else: 

879 self._api.fail(f'Unsupported "__set__" in "{t.type.name}"', context) 

880 

881 return default 1a

882 

883 def add_initializer( 1a

884 self, fields: list[PydanticModelField], config: ModelConfigData, is_settings: bool, is_root_model: bool 

885 ) -> None: 

886 """Adds a fields-aware `__init__` method to the class. 

887 

888 The added `__init__` will be annotated with types vs. all `Any` depending on the plugin settings. 

889 """ 

890 if ( 

891 '__init__' in self._cls.info.names 

892 and not self._cls.info.names['__init__'].plugin_generated 

893 # `RootModel` declares a typed `__init__` for the benefit of type checkers when the plugin 

894 # isn't used, but the plugin-generated one should take priority over it: 

895 and self._cls.fullname != ROOT_MODEL_FULLNAME 

896 ): 

897 return # Don't generate an __init__ if one already exists 1a

898 

899 typed = self.plugin_config.init_typed 1a

900 model_strict = bool(config.strict) 1a

901 use_alias = not (config.validate_by_name or config.populate_by_name) and config.validate_by_alias is not False 1a

902 requires_dynamic_aliases = bool(config.has_alias_generator and not config.validate_by_name) 1a

903 args = self.get_field_arguments( 1a

904 fields, 

905 typed=typed, 

906 model_strict=model_strict, 

907 requires_dynamic_aliases=requires_dynamic_aliases, 

908 use_alias=use_alias, 

909 is_settings=is_settings, 

910 is_root_model=is_root_model, 

911 force_typevars_invariant=True, 

912 ) 

913 

914 if is_settings: 1a

915 base_settings_node = self._api.lookup_fully_qualified(BASESETTINGS_FULLNAME).node 1a

916 assert isinstance(base_settings_node, TypeInfo) 1a

917 if '__init__' in base_settings_node.names: 917 ↛ 940line 917 didn't jump to line 940 because the condition on line 917 was always true1a

918 base_settings_init_node = base_settings_node.names['__init__'].node 1a

919 assert isinstance(base_settings_init_node, FuncDef) 1a

920 if base_settings_init_node is not None and base_settings_init_node.type is not None: 920 ↛ 940line 920 didn't jump to line 940 because the condition on line 920 was always true1a

921 func_type = base_settings_init_node.type 1a

922 assert isinstance(func_type, CallableType) 1a

923 for arg_idx, arg_name in enumerate(func_type.arg_names): 1a

924 if arg_name is None or arg_name.startswith('__') or not arg_name.startswith('_'): 1a

925 continue 1a

926 analyzed_variable_type = self._api.anal_type(func_type.arg_types[arg_idx]) 1a

927 if analyzed_variable_type is not None and arg_name in ( 1a

928 '_cli_settings_source', 

929 '_build_sources', 

930 ): 

931 # These arg names are annotated with types explicitly parameterized with `Any`, and as such 

932 # the Any causes issues with --disallow-any-explicit. As a workaround, change 

933 # the Any type (as if the generic type was left unparameterized): 

934 analyzed_variable_type = analyzed_variable_type.accept( 1a

935 ChangeExplicitTypeOfAny(TypeOfAny.from_omitted_generics) 

936 ) 

937 variable = Var(arg_name, analyzed_variable_type) 1a

938 args.append(Argument(variable, analyzed_variable_type, None, ARG_OPT)) 1a

939 

940 if not self.should_init_forbid_extra(fields, config): 1a

941 var = Var('kwargs') 1a

942 args.append(Argument(var, AnyType(TypeOfAny.special_form), None, ARG_STAR2)) 1a

943 

944 add_method(self._api, self._cls, '__init__', args=args, return_type=NoneType()) 1a

945 

946 def add_model_construct_method( 1a

947 self, 

948 fields: list[PydanticModelField], 

949 config: ModelConfigData, 

950 is_settings: bool, 

951 is_root_model: bool, 

952 ) -> None: 

953 """Adds a fully typed `model_construct` classmethod to the class. 

954 

955 Similar to the fields-aware __init__ method, but always uses the field names (not aliases), 

956 and does not treat settings fields as optional. 

957 """ 

958 set_str = self._api.named_type(f'{BUILTINS_NAME}.set', [self._api.named_type(f'{BUILTINS_NAME}.str')]) 1a

959 optional_set_str = UnionType([set_str, NoneType()]) 1a

960 fields_set_argument = Argument(Var('_fields_set', optional_set_str), optional_set_str, None, ARG_OPT) 1a

961 with state.strict_optional_set(self._api.options.strict_optional): 1a

962 args = self.get_field_arguments( 1a

963 fields, 

964 typed=True, 

965 model_strict=bool(config.strict), 

966 requires_dynamic_aliases=False, 

967 use_alias=False, 

968 is_settings=is_settings, 

969 is_root_model=is_root_model, 

970 ) 

971 if not self.should_init_forbid_extra(fields, config): 1a

972 var = Var('kwargs') 1a

973 args.append(Argument(var, AnyType(TypeOfAny.special_form), None, ARG_STAR2)) 1a

974 

975 args = args + [fields_set_argument] if is_root_model else [fields_set_argument] + args 1a

976 

977 add_method( 1a

978 self._api, 

979 self._cls, 

980 'model_construct', 

981 args=args, 

982 return_type=fill_typevars(self._cls.info), 

983 is_classmethod=True, 

984 ) 

985 

986 def set_frozen(self, fields: list[PydanticModelField], api: SemanticAnalyzerPluginInterface, frozen: bool) -> None: 1a

987 """Marks all fields as properties so that attempts to set them trigger mypy errors. 

988 

989 This is the same approach used by the attrs and dataclasses plugins. 

990 """ 

991 info = self._cls.info 1a

992 for field in fields: 1a

993 sym_node = info.names.get(field.name) 1a

994 if sym_node is not None: 1a

995 var = sym_node.node 1a

996 if isinstance(var, Var): 1a

997 var.is_property = frozen or field.is_frozen 1a

998 elif isinstance(var, PlaceholderNode) and not self._api.final_iteration: 998 ↛ 1000line 998 didn't jump to line 1000 because the condition on line 998 was never true1a

999 # See https://github.com/pydantic/pydantic/issues/5191 to hit this branch for test coverage 

1000 self._api.defer() 

1001 # `var` can also be a FuncDef or Decorator node (e.g. when overriding a field with a function or property). 

1002 # In that case, we don't want to do anything. Mypy will already raise an error that a field was not properly 

1003 # overridden. 

1004 else: 

1005 var = field.to_var(info, api, use_alias=False) 1a

1006 var.info = info 1a

1007 var.is_property = frozen 1a

1008 var._fullname = info.fullname + '.' + var.name 1a

1009 info.names[var.name] = SymbolTableNode(MDEF, var) 1a

1010 

1011 def get_config_update(self, name: str, arg: Expression, lax_extra: bool = False) -> ModelConfigData | None: 1a

1012 """Determines the config update due to a single kwarg in the ConfigDict definition. 

1013 

1014 Warns if a tracked config attribute is set to a value the plugin doesn't know how to interpret (e.g., an int) 

1015 """ 

1016 if name not in self.tracked_config_fields: 1a

1017 return None 1a

1018 if name == 'extra': 1a

1019 if isinstance(arg, StrExpr): 1a

1020 forbid_extra = arg.value == 'forbid' 1a

1021 else: 

1022 if not lax_extra: 1a

1023 # Only emit an error for other types of `arg` (e.g., `NameExpr`, `ConditionalExpr`, etc.) when 

1024 # reading from class kwargs or a dict literal. If a ConfigDict is used, then we don't want to emit an error 

1025 # because you'll get type checking from the ConfigDict itself. 

1026 # 

1027 # It would be nice if we could introspect the types better otherwise, but I don't know what the API 

1028 # is to evaluate an expr into its type and then check if that type is compatible with the expected 

1029 # type. Note that you can still get proper type checking via: `model_config = ConfigDict(...)`, just 

1030 # if you don't use an explicit string, the plugin won't be able to infer whether extra is forbidden. 

1031 error_invalid_config_value(name, self._api, arg) 1a

1032 return None 1a

1033 return ModelConfigData(forbid_extra=forbid_extra) 1a

1034 if name == 'alias_generator': 1a

1035 has_alias_generator = True 1a

1036 if isinstance(arg, NameExpr) and arg.fullname == 'builtins.None': 1a

1037 has_alias_generator = False 1a

1038 return ModelConfigData(has_alias_generator=has_alias_generator) 1a

1039 if isinstance(arg, NameExpr) and arg.fullname in ('builtins.True', 'builtins.False'): 1a

1040 return ModelConfigData(**{name: arg.fullname == 'builtins.True'}) 1a

1041 error_invalid_config_value(name, self._api, arg) 1a

1042 return None 1a

1043 

1044 @staticmethod 1a

1045 def get_has_default(stmt: AssignmentStmt) -> bool: 1a

1046 """Returns a boolean indicating whether the field defined in `stmt` is a required field.""" 

1047 expr = stmt.rvalue 1a

1048 if isinstance(expr, TempNode): 1a

1049 # TempNode means annotation-only, so has no default 

1050 return False 1a

1051 if isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME: 1a

1052 # The "default value" is a call to `Field`; at this point, the field has a default if and only if: 

1053 # * there is a positional argument that is not `...` 

1054 # * there is a keyword argument named "default" that is not `...` 

1055 # * there is a "default_factory" that is not `None` 

1056 for arg, name in zip(expr.args, expr.arg_names, strict=True): 1a

1057 # If name is None, then this arg is the default because it is the only positional argument. 

1058 if name is None or name == 'default': 1a

1059 return arg.__class__ is not EllipsisExpr 1a

1060 if name == 'default_factory': 1a

1061 return not (isinstance(arg, NameExpr) and arg.fullname == 'builtins.None') 1a

1062 return False 1a

1063 # Has no default if the "default value" is Ellipsis (i.e., `field_name: Annotation = ...`) 

1064 return not isinstance(expr, EllipsisExpr) 1a

1065 

1066 @staticmethod 1a

1067 def get_strict(stmt: AssignmentStmt) -> bool | None: 1a

1068 """Returns the `strict` value of a field if defined, otherwise `None`.""" 

1069 expr = stmt.rvalue 1a

1070 if isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME: 1a

1071 for arg, name in zip(expr.args, expr.arg_names, strict=True): 1a

1072 if name != 'strict': 1a

1073 continue 1a

1074 if isinstance(arg, NameExpr): 1074 ↛ 1079line 1074 didn't jump to line 1079 because the condition on line 1074 was always true1a

1075 if arg.fullname == 'builtins.True': 1a

1076 return True 1a

1077 elif arg.fullname == 'builtins.False': 1077 ↛ 1079line 1077 didn't jump to line 1079 because the condition on line 1077 was always true1a

1078 return False 1a

1079 return None 

1080 return None 1a

1081 

1082 @staticmethod 1a

1083 def get_alias_info(stmt: AssignmentStmt) -> tuple[str | None, bool]: 1a

1084 """Returns a pair (alias, has_dynamic_alias), extracted from the declaration of the field defined in `stmt`. 

1085 

1086 `has_dynamic_alias` is True if and only if an alias is provided, but not as a string literal. 

1087 If `has_dynamic_alias` is True, `alias` will be None. 

1088 """ 

1089 expr = stmt.rvalue 1a

1090 if isinstance(expr, TempNode): 1a

1091 # TempNode means annotation-only 

1092 return None, False 1a

1093 

1094 if not ( 

1095 isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME 

1096 ): 

1097 # Assigned value is not a call to pydantic.fields.Field 

1098 return None, False 1a

1099 

1100 if 'validation_alias' in expr.arg_names: 1a

1101 arg = expr.args[expr.arg_names.index('validation_alias')] 1a

1102 elif 'alias' in expr.arg_names: 1a

1103 arg = expr.args[expr.arg_names.index('alias')] 1a

1104 else: 

1105 return None, False 1a

1106 

1107 if isinstance(arg, StrExpr): 1a

1108 return arg.value, False 1a

1109 else: 

1110 return None, True 1a

1111 

1112 @staticmethod 1a

1113 def is_field_frozen(stmt: AssignmentStmt) -> bool: 1a

1114 """Returns whether the field is frozen, extracted from the declaration of the field defined in `stmt`. 

1115 

1116 Note that this is only whether the field was declared to be frozen in a `<field_name> = Field(frozen=True)` 

1117 sense; this does not determine whether the field is frozen because the entire model is frozen; that is 

1118 handled separately. 

1119 """ 

1120 expr = stmt.rvalue 1a

1121 if isinstance(expr, TempNode): 1a

1122 # TempNode means annotation-only 

1123 return False 1a

1124 

1125 if not ( 

1126 isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME 

1127 ): 

1128 # Assigned value is not a call to pydantic.fields.Field 

1129 return False 1a

1130 

1131 for i, arg_name in enumerate(expr.arg_names): 1a

1132 if arg_name == 'frozen': 1a

1133 arg = expr.args[i] 1a

1134 return isinstance(arg, NameExpr) and arg.fullname == 'builtins.True' 1a

1135 return False 1a

1136 

1137 def get_field_arguments( 1a

1138 self, 

1139 fields: list[PydanticModelField], 

1140 typed: bool, 

1141 model_strict: bool, 

1142 use_alias: bool, 

1143 requires_dynamic_aliases: bool, 

1144 is_settings: bool, 

1145 is_root_model: bool, 

1146 force_typevars_invariant: bool = False, 

1147 ) -> list[Argument]: 

1148 """Helper function used during the construction of the `__init__` and `model_construct` method signatures. 

1149 

1150 Returns a list of mypy Argument instances for use in the generated signatures. 

1151 """ 

1152 info = self._cls.info 1a

1153 arguments = [ 1a

1154 field.to_argument( 

1155 info, 

1156 typed=typed, 

1157 model_strict=model_strict, 

1158 force_optional=requires_dynamic_aliases or is_settings, 

1159 use_alias=use_alias, 

1160 api=self._api, 

1161 force_typevars_invariant=force_typevars_invariant, 

1162 is_root_model_root=is_root_model and field.name == 'root', 

1163 ) 

1164 for field in fields 

1165 if not (use_alias and field.has_dynamic_alias) 

1166 ] 

1167 return arguments 1a

1168 

1169 def should_init_forbid_extra(self, fields: list[PydanticModelField], config: ModelConfigData) -> bool: 1a

1170 """Indicates whether the generated `__init__` should get a `**kwargs` at the end of its signature. 

1171 

1172 We disallow arbitrary kwargs if the extra config setting is "forbid", or if the plugin config says to, 

1173 *unless* a required dynamic alias is present (since then we can't determine a valid signature). 

1174 """ 

1175 if not (config.validate_by_name or config.populate_by_name): 1a

1176 if self.is_dynamic_alias_present(fields, bool(config.has_alias_generator)): 1a

1177 return False 1a

1178 if config.forbid_extra: 1a

1179 return True 1a

1180 return self.plugin_config.init_forbid_extra 1a

1181 

1182 @staticmethod 1a

1183 def is_dynamic_alias_present(fields: list[PydanticModelField], has_alias_generator: bool) -> bool: 1a

1184 """Returns whether any fields on the model have a "dynamic alias", i.e., an alias that cannot be 

1185 determined during static analysis. 

1186 """ 

1187 for field in fields: 1a

1188 if field.has_dynamic_alias: 1a

1189 return True 1a

1190 if has_alias_generator: 1a

1191 for field in fields: 1a

1192 if field.alias is None: 1a

1193 return True 1a

1194 return False 1a

1195 

1196 

1197class ChangeExplicitTypeOfAny(TypeTranslator): 1a

1198 """A type translator used to change type of Any's, if explicit.""" 

1199 

1200 def __init__(self, type_of_any: int) -> None: 1a

1201 self._type_of_any = type_of_any 1a

1202 super().__init__() 1a

1203 

1204 def visit_any(self, t: AnyType) -> Type: # noqa: D102 1a

1205 if t.type_of_any == TypeOfAny.explicit: 1a

1206 return t.copy_modified(type_of_any=self._type_of_any) 1a

1207 else: 

1208 return t 1a

1209 

1210 

1211class ModelConfigData: 1a

1212 """Pydantic mypy plugin model config class.""" 

1213 

1214 def __init__( 1a

1215 self, 

1216 forbid_extra: bool | None = None, 

1217 frozen: bool | None = None, 

1218 populate_by_name: bool | None = None, 

1219 validate_by_alias: bool | None = None, 

1220 validate_by_name: bool | None = None, 

1221 has_alias_generator: bool | None = None, 

1222 strict: bool | None = None, 

1223 ): 

1224 self.forbid_extra = forbid_extra 1a

1225 self.frozen = frozen 1a

1226 self.populate_by_name = populate_by_name 1a

1227 self.validate_by_alias = validate_by_alias 1a

1228 self.validate_by_name = validate_by_name 1a

1229 self.has_alias_generator = has_alias_generator 1a

1230 self.strict = strict 1a

1231 

1232 def get_values_dict(self) -> dict[str, Any]: 1a

1233 """Returns a dict of Pydantic model config names to their values. 

1234 

1235 It includes the config if config value is not `None`. 

1236 """ 

1237 return {k: v for k, v in self.__dict__.items() if v is not None} 1a

1238 

1239 def update(self, config: ModelConfigData | None) -> None: 1a

1240 """Update Pydantic model config values.""" 

1241 if config is None: 1a

1242 return 1a

1243 for k, v in config.get_values_dict().items(): 1a

1244 setattr(self, k, v) 1a

1245 

1246 def setdefault(self, key: str, value: Any) -> None: 1a

1247 """Set default value for Pydantic model config if config value is `None`.""" 

1248 if getattr(self, key) is None: 1a

1249 setattr(self, key, value) 1a

1250 

1251 

1252def is_root_model(info: TypeInfo) -> bool: 1a

1253 """Return whether the type info is a root model subclass (or the `RootModel` class itself).""" 

1254 return info.has_base(ROOT_MODEL_FULLNAME) 1a

1255 

1256 

1257ERROR_CONFIG = ErrorCode('pydantic-config', 'Invalid config value', 'Pydantic') 1a

1258ERROR_ALIAS = ErrorCode('pydantic-alias', 'Dynamic alias disallowed', 'Pydantic') 1a

1259ERROR_UNEXPECTED = ErrorCode('pydantic-unexpected', 'Unexpected behavior', 'Pydantic') 1a

1260ERROR_UNTYPED = ErrorCode('pydantic-field', 'Untyped field disallowed', 'Pydantic') 1a

1261ERROR_FIELD_DEFAULTS = ErrorCode('pydantic-field', 'Invalid Field defaults', 'Pydantic') 1a

1262ERROR_EXTRA_FIELD_ROOT_MODEL = ErrorCode('pydantic-field', 'Extra field on RootModel subclass', 'Pydantic') 1a

1263 

1264 

1265def error_invalid_config_value(name: str, api: SemanticAnalyzerPluginInterface, context: Context) -> None: 1a

1266 """Emits an error when the config value is invalid.""" 

1267 api.fail(f'Invalid value for "Config.{name}"', context, code=ERROR_CONFIG) 1a

1268 

1269 

1270def error_required_dynamic_aliases(api: SemanticAnalyzerPluginInterface, context: Context) -> None: 1a

1271 """Emits required dynamic aliases error. 

1272 

1273 This will be called when `warn_required_dynamic_aliases=True`. 

1274 """ 

1275 api.fail('Required dynamic aliases disallowed', context, code=ERROR_ALIAS) 1a

1276 

1277 

1278def error_unexpected_behavior( 1a

1279 detail: str, api: CheckerPluginInterface | SemanticAnalyzerPluginInterface, context: Context 1a

1280) -> None: # pragma: no cover 1a

1281 """Emits unexpected behavior error.""" 

1282 # Can't think of a good way to test this, but I confirmed it renders as desired by adding to a non-error path 

1283 link = 'https://github.com/pydantic/pydantic/issues/new/choose' 

1284 full_message = f'The pydantic mypy plugin ran into unexpected behavior: {detail}\n' 

1285 full_message += f'Please consider reporting this bug at {link} so we can try to fix it!' 

1286 api.fail(full_message, context, code=ERROR_UNEXPECTED) 

1287 

1288 

1289def error_untyped_fields(api: SemanticAnalyzerPluginInterface, context: Context) -> None: 1a

1290 """Emits an error when there is an untyped field in the model.""" 

1291 api.fail('Untyped fields disallowed', context, code=ERROR_UNTYPED) 1a

1292 

1293 

1294def error_extra_fields_on_root_model(api: CheckerPluginInterface, context: Context) -> None: 1a

1295 """Emits an error when there is more than just a root field defined for a subclass of RootModel.""" 

1296 api.fail('Only `root` is allowed as a field of a `RootModel`', context, code=ERROR_EXTRA_FIELD_ROOT_MODEL) 1a

1297 

1298 

1299def add_method( 1a

1300 api: SemanticAnalyzerPluginInterface | CheckerPluginInterface, 

1301 cls: ClassDef, 

1302 name: str, 

1303 args: list[Argument], 

1304 return_type: Type, 

1305 self_type: Type | None = None, 

1306 tvar_def: TypeVarType | None = None, 

1307 is_classmethod: bool = False, 

1308) -> None: 

1309 """Very closely related to `mypy.plugins.common.add_method_to_class`, with a few pydantic-specific changes.""" 

1310 info = cls.info 1a

1311 

1312 # First remove any previously generated methods with the same name 

1313 # to avoid clashes and problems in the semantic analyzer. 

1314 if name in info.names: 1a

1315 sym = info.names[name] 1a

1316 if sym.plugin_generated and isinstance(sym.node, FuncDef): 1a

1317 cls.defs.body.remove(sym.node) # pragma: no cover 1a

1318 

1319 if isinstance(api, SemanticAnalyzerPluginInterface): 1319 ↛ 1322line 1319 didn't jump to line 1322 because the condition on line 1319 was always true1a

1320 function_type = api.named_type('builtins.function') 1a

1321 else: 

1322 function_type = api.named_generic_type('builtins.function', []) 

1323 

1324 if is_classmethod: 1a

1325 self_type = self_type or TypeType(fill_typevars(info)) 1a

1326 first = [Argument(Var('_cls'), self_type, None, ARG_POS, True)] 1a

1327 else: 

1328 self_type = self_type or fill_typevars(info) 1a

1329 # `self` is positional *ONLY* here, but this can't be expressed 

1330 # fully in the mypy internal API. ARG_POS is the closest we can get. 

1331 # Using ARG_POS will, however, give mypy errors if a `self` field 

1332 # is present on a model: 

1333 # 

1334 # Name "self" already defined (possibly by an import) [no-redef] 

1335 # 

1336 # As a workaround, we give this argument a name that will 

1337 # never conflict. By its positional nature, this name will not 

1338 # be used or exposed to users. 

1339 first = [Argument(Var('__pydantic_self__'), self_type, None, ARG_POS)] 1a

1340 args = first + args 1a

1341 

1342 arg_types, arg_names, arg_kinds = [], [], [] 1a

1343 for arg in args: 1a

1344 assert arg.type_annotation, 'All arguments must be fully typed.' 1a

1345 arg_types.append(arg.type_annotation) 1a

1346 arg_names.append(arg.variable.name) 1a

1347 arg_kinds.append(arg.kind) 1a

1348 

1349 signature = CallableType( 1a

1350 arg_types, arg_kinds, arg_names, return_type, function_type, variables=[tvar_def] if tvar_def else None 

1351 ) 

1352 

1353 func = FuncDef(name, args, Block([PassStmt()])) 1a

1354 func.info = info 1a

1355 func.type = set_callable_name(signature, func) 1a

1356 func.is_class = is_classmethod 1a

1357 func._fullname = info.fullname + '.' + name 1a

1358 func.line = info.line 1a

1359 

1360 # NOTE: we would like the plugin generated node to dominate, but we still 

1361 # need to keep any existing definitions so they get semantically analyzed. 

1362 if name in info.names: 1a

1363 # Get a nice unique name instead. 

1364 r_name = get_unique_redefinition_name(name, info.names) 1a

1365 info.names[r_name] = info.names[name] 1a

1366 

1367 # Add decorator for is_classmethod 

1368 # The dataclasses plugin claims this is unnecessary for classmethods, but not including it results in a 

1369 # signature incompatible with the superclass, which causes mypy errors to occur for every subclass of BaseModel. 

1370 if is_classmethod: 1a

1371 func.is_decorated = True 1a

1372 v = Var(name, func.type) 1a

1373 v.info = info 1a

1374 v._fullname = func._fullname 1a

1375 v.is_classmethod = True 1a

1376 dec = Decorator(func, [NameExpr('classmethod')], v) 1a

1377 dec.line = info.line 1a

1378 sym = SymbolTableNode(MDEF, dec) 1a

1379 else: 

1380 sym = SymbolTableNode(MDEF, func) 1a

1381 sym.plugin_generated = True 1a

1382 info.names[name] = sym 1a

1383 

1384 info.defn.defs.body.append(func) 1a

1385 

1386 

1387def parse_toml(config_file: str) -> dict[str, Any] | None: 1a

1388 """Returns a dict of config keys to values. 

1389 

1390 It reads configs from toml file and returns `None` if the file is not a toml file. 

1391 """ 

1392 if not config_file.endswith('.toml'): 1a

1393 return None 1a

1394 

1395 with open(config_file, 'rb') as rf: 1a

1396 return tomllib.load(rf) 1a