pboot-validator 1.0.0__py3-none-any.whl

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