datamodel-code-generator 0.27.2__py3-none-any.whl → 0.27.3__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.

Potentially problematic release.


This version of datamodel-code-generator might be problematic. Click here for more details.

Files changed (43) hide show
  1. datamodel_code_generator/__init__.py +159 -190
  2. datamodel_code_generator/__main__.py +151 -173
  3. datamodel_code_generator/arguments.py +227 -230
  4. datamodel_code_generator/format.py +77 -99
  5. datamodel_code_generator/http.py +9 -10
  6. datamodel_code_generator/imports.py +57 -64
  7. datamodel_code_generator/model/__init__.py +26 -31
  8. datamodel_code_generator/model/base.py +94 -127
  9. datamodel_code_generator/model/dataclass.py +58 -59
  10. datamodel_code_generator/model/enum.py +34 -30
  11. datamodel_code_generator/model/imports.py +13 -11
  12. datamodel_code_generator/model/msgspec.py +112 -126
  13. datamodel_code_generator/model/pydantic/__init__.py +14 -27
  14. datamodel_code_generator/model/pydantic/base_model.py +120 -139
  15. datamodel_code_generator/model/pydantic/custom_root_type.py +2 -2
  16. datamodel_code_generator/model/pydantic/dataclass.py +6 -4
  17. datamodel_code_generator/model/pydantic/imports.py +35 -33
  18. datamodel_code_generator/model/pydantic/types.py +86 -117
  19. datamodel_code_generator/model/pydantic_v2/__init__.py +17 -17
  20. datamodel_code_generator/model/pydantic_v2/base_model.py +118 -119
  21. datamodel_code_generator/model/pydantic_v2/imports.py +5 -3
  22. datamodel_code_generator/model/pydantic_v2/root_model.py +6 -6
  23. datamodel_code_generator/model/pydantic_v2/types.py +8 -7
  24. datamodel_code_generator/model/rootmodel.py +1 -1
  25. datamodel_code_generator/model/scalar.py +33 -32
  26. datamodel_code_generator/model/typed_dict.py +42 -41
  27. datamodel_code_generator/model/types.py +19 -17
  28. datamodel_code_generator/model/union.py +21 -17
  29. datamodel_code_generator/parser/__init__.py +12 -11
  30. datamodel_code_generator/parser/base.py +320 -492
  31. datamodel_code_generator/parser/graphql.py +80 -111
  32. datamodel_code_generator/parser/jsonschema.py +422 -580
  33. datamodel_code_generator/parser/openapi.py +175 -204
  34. datamodel_code_generator/pydantic_patch.py +8 -9
  35. datamodel_code_generator/reference.py +192 -274
  36. datamodel_code_generator/types.py +147 -182
  37. datamodel_code_generator/util.py +22 -26
  38. {datamodel_code_generator-0.27.2.dist-info → datamodel_code_generator-0.27.3.dist-info}/METADATA +7 -1
  39. datamodel_code_generator-0.27.3.dist-info/RECORD +59 -0
  40. datamodel_code_generator-0.27.2.dist-info/RECORD +0 -59
  41. {datamodel_code_generator-0.27.2.dist-info → datamodel_code_generator-0.27.3.dist-info}/WHEEL +0 -0
  42. {datamodel_code_generator-0.27.2.dist-info → datamodel_code_generator-0.27.3.dist-info}/entry_points.txt +0 -0
  43. {datamodel_code_generator-0.27.2.dist-info → datamodel_code_generator-0.27.3.dist-info}/licenses/LICENSE +0 -0
@@ -1,7 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  from decimal import Decimal
4
- from typing import Any, ClassVar, Dict, Optional, Sequence, Set, Type
4
+ from typing import Any, ClassVar, Sequence
5
5
 
6
6
  from datamodel_code_generator.format import DatetimeClassType, PythonVersion
7
7
  from datamodel_code_generator.imports import (
@@ -55,15 +55,15 @@ from datamodel_code_generator.types import DataTypeManager as _DataTypeManager
55
55
 
56
56
 
57
57
  def type_map_factory(
58
- data_type: Type[DataType],
58
+ data_type: type[DataType],
59
59
  strict_types: Sequence[StrictTypes],
60
60
  pattern_key: str,
61
- use_pendulum: bool,
62
- target_datetime_class: DatetimeClassType,
63
- ) -> Dict[Types, DataType]:
64
- data_type_int = data_type(type='int')
65
- data_type_float = data_type(type='float')
66
- data_type_str = data_type(type='str')
61
+ use_pendulum: bool, # noqa: FBT001
62
+ target_datetime_class: DatetimeClassType, # noqa: ARG001
63
+ ) -> dict[Types, DataType]:
64
+ data_type_int = data_type(type="int")
65
+ data_type_float = data_type(type="float")
66
+ data_type_str = data_type(type="str")
67
67
  result = {
68
68
  Types.integer: data_type_int,
69
69
  Types.int32: data_type_int,
@@ -75,7 +75,7 @@ def type_map_factory(
75
75
  Types.time: data_type.from_import(IMPORT_TIME),
76
76
  Types.string: data_type_str,
77
77
  Types.byte: data_type_str, # base64 encoded string
78
- Types.binary: data_type(type='bytes'),
78
+ Types.binary: data_type(type="bytes"),
79
79
  Types.date: data_type.from_import(IMPORT_DATE),
80
80
  Types.date_time: data_type.from_import(IMPORT_DATETIME),
81
81
  Types.timedelta: data_type.from_import(IMPORT_TIMEDELTA),
@@ -94,17 +94,18 @@ def type_map_factory(
94
94
  strict=StrictTypes.str in strict_types,
95
95
  # https://github.com/horejsek/python-fastjsonschema/blob/61c6997a8348b8df9b22e029ca2ba35ef441fbb8/fastjsonschema/draft04.py#L31
96
96
  kwargs={
97
- pattern_key: r"r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9])\Z'",
98
- **({'strict': True} if StrictTypes.str in strict_types else {}),
97
+ pattern_key: r"r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])\.)*"
98
+ r"([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9])\Z'",
99
+ **({"strict": True} if StrictTypes.str in strict_types else {}),
99
100
  },
100
101
  ),
101
102
  Types.ipv4: data_type.from_import(IMPORT_IPV4ADDRESS),
102
103
  Types.ipv6: data_type.from_import(IMPORT_IPV6ADDRESS),
103
104
  Types.ipv4_network: data_type.from_import(IMPORT_IPV4NETWORKS),
104
105
  Types.ipv6_network: data_type.from_import(IMPORT_IPV6NETWORKS),
105
- Types.boolean: data_type(type='bool'),
106
+ Types.boolean: data_type(type="bool"),
106
107
  Types.object: data_type.from_import(IMPORT_ANY, is_dict=True),
107
- Types.null: data_type(type='None'),
108
+ Types.null: data_type(type="None"),
108
109
  Types.array: data_type.from_import(IMPORT_ANY, is_list=True),
109
110
  Types.any: data_type.from_import(IMPORT_ANY),
110
111
  }
@@ -117,7 +118,7 @@ def type_map_factory(
117
118
  return result
118
119
 
119
120
 
120
- def strict_type_map_factory(data_type: Type[DataType]) -> Dict[StrictTypes, DataType]:
121
+ def strict_type_map_factory(data_type: type[DataType]) -> dict[StrictTypes, DataType]:
121
122
  return {
122
123
  StrictTypes.int: data_type.from_import(IMPORT_STRICT_INT, strict=True),
123
124
  StrictTypes.float: data_type.from_import(IMPORT_STRICT_FLOAT, strict=True),
@@ -127,44 +128,42 @@ def strict_type_map_factory(data_type: Type[DataType]) -> Dict[StrictTypes, Data
127
128
  }
128
129
 
129
130
 
130
- number_kwargs: Set[str] = {
131
- 'exclusiveMinimum',
132
- 'minimum',
133
- 'exclusiveMaximum',
134
- 'maximum',
135
- 'multipleOf',
131
+ number_kwargs: set[str] = {
132
+ "exclusiveMinimum",
133
+ "minimum",
134
+ "exclusiveMaximum",
135
+ "maximum",
136
+ "multipleOf",
136
137
  }
137
138
 
138
- string_kwargs: Set[str] = {'minItems', 'maxItems', 'minLength', 'maxLength', 'pattern'}
139
+ string_kwargs: set[str] = {"minItems", "maxItems", "minLength", "maxLength", "pattern"}
139
140
 
140
- byes_kwargs: Set[str] = {'minLength', 'maxLength'}
141
+ byes_kwargs: set[str] = {"minLength", "maxLength"}
141
142
 
142
- escape_characters = str.maketrans(
143
- {
144
- "'": r'\'',
145
- '\b': r'\b',
146
- '\f': r'\f',
147
- '\n': r'\n',
148
- '\r': r'\r',
149
- '\t': r'\t',
150
- }
151
- )
143
+ escape_characters = str.maketrans({
144
+ "'": r"\'",
145
+ "\b": r"\b",
146
+ "\f": r"\f",
147
+ "\n": r"\n",
148
+ "\r": r"\r",
149
+ "\t": r"\t",
150
+ })
152
151
 
153
152
 
154
153
  class DataTypeManager(_DataTypeManager):
155
- PATTERN_KEY: ClassVar[str] = 'regex'
154
+ PATTERN_KEY: ClassVar[str] = "regex"
156
155
 
157
- def __init__(
156
+ def __init__( # noqa: PLR0913, PLR0917
158
157
  self,
159
158
  python_version: PythonVersion = PythonVersion.PY_38,
160
- use_standard_collections: bool = False,
161
- use_generic_container_types: bool = False,
162
- strict_types: Optional[Sequence[StrictTypes]] = None,
163
- use_non_positive_negative_number_constrained_types: bool = False,
164
- use_union_operator: bool = False,
165
- use_pendulum: bool = False,
166
- target_datetime_class: Optional[DatetimeClassType] = None,
167
- ):
159
+ use_standard_collections: bool = False, # noqa: FBT001, FBT002
160
+ use_generic_container_types: bool = False, # noqa: FBT001, FBT002
161
+ strict_types: Sequence[StrictTypes] | None = None,
162
+ use_non_positive_negative_number_constrained_types: bool = False, # noqa: FBT001, FBT002
163
+ use_union_operator: bool = False, # noqa: FBT001, FBT002
164
+ use_pendulum: bool = False, # noqa: FBT001, FBT002
165
+ target_datetime_class: DatetimeClassType | None = None,
166
+ ) -> None:
168
167
  super().__init__(
169
168
  python_version,
170
169
  use_standard_collections,
@@ -176,36 +175,36 @@ class DataTypeManager(_DataTypeManager):
176
175
  target_datetime_class,
177
176
  )
178
177
 
179
- self.type_map: Dict[Types, DataType] = self.type_map_factory(
178
+ self.type_map: dict[Types, DataType] = self.type_map_factory(
180
179
  self.data_type,
181
180
  strict_types=self.strict_types,
182
181
  pattern_key=self.PATTERN_KEY,
183
182
  target_datetime_class=self.target_datetime_class,
184
183
  )
185
- self.strict_type_map: Dict[StrictTypes, DataType] = strict_type_map_factory(
184
+ self.strict_type_map: dict[StrictTypes, DataType] = strict_type_map_factory(
186
185
  self.data_type,
187
186
  )
188
187
 
189
- self.kwargs_schema_to_model: Dict[str, str] = {
190
- 'exclusiveMinimum': 'gt',
191
- 'minimum': 'ge',
192
- 'exclusiveMaximum': 'lt',
193
- 'maximum': 'le',
194
- 'multipleOf': 'multiple_of',
195
- 'minItems': 'min_items',
196
- 'maxItems': 'max_items',
197
- 'minLength': 'min_length',
198
- 'maxLength': 'max_length',
199
- 'pattern': self.PATTERN_KEY,
188
+ self.kwargs_schema_to_model: dict[str, str] = {
189
+ "exclusiveMinimum": "gt",
190
+ "minimum": "ge",
191
+ "exclusiveMaximum": "lt",
192
+ "maximum": "le",
193
+ "multipleOf": "multiple_of",
194
+ "minItems": "min_items",
195
+ "maxItems": "max_items",
196
+ "minLength": "min_length",
197
+ "maxLength": "max_length",
198
+ "pattern": self.PATTERN_KEY,
200
199
  }
201
200
 
202
201
  def type_map_factory(
203
202
  self,
204
- data_type: Type[DataType],
203
+ data_type: type[DataType],
205
204
  strict_types: Sequence[StrictTypes],
206
205
  pattern_key: str,
207
- target_datetime_class: DatetimeClassType,
208
- ) -> Dict[Types, DataType]:
206
+ target_datetime_class: DatetimeClassType, # noqa: ARG002
207
+ ) -> dict[Types, DataType]:
209
208
  return type_map_factory(
210
209
  data_type,
211
210
  strict_types,
@@ -214,47 +213,35 @@ class DataTypeManager(_DataTypeManager):
214
213
  self.target_datetime_class,
215
214
  )
216
215
 
217
- def transform_kwargs(
218
- self, kwargs: Dict[str, Any], filter_: Set[str]
219
- ) -> Dict[str, str]:
220
- return {
221
- self.kwargs_schema_to_model.get(k, k): v
222
- for (k, v) in kwargs.items()
223
- if v is not None and k in filter_
224
- }
216
+ def transform_kwargs(self, kwargs: dict[str, Any], filter_: set[str]) -> dict[str, str]:
217
+ return {self.kwargs_schema_to_model.get(k, k): v for (k, v) in kwargs.items() if v is not None and k in filter_}
225
218
 
226
- def get_data_int_type(
219
+ def get_data_int_type( # noqa: PLR0911
227
220
  self,
228
221
  types: Types,
229
222
  **kwargs: Any,
230
223
  ) -> DataType:
231
- data_type_kwargs: Dict[str, Any] = self.transform_kwargs(kwargs, number_kwargs)
224
+ data_type_kwargs: dict[str, Any] = self.transform_kwargs(kwargs, number_kwargs)
232
225
  strict = StrictTypes.int in self.strict_types
233
226
  if data_type_kwargs:
234
227
  if not strict:
235
- if data_type_kwargs == {'gt': 0}:
228
+ if data_type_kwargs == {"gt": 0}:
236
229
  return self.data_type.from_import(IMPORT_POSITIVE_INT)
237
- if data_type_kwargs == {'lt': 0}:
230
+ if data_type_kwargs == {"lt": 0}:
238
231
  return self.data_type.from_import(IMPORT_NEGATIVE_INT)
239
- if (
240
- data_type_kwargs == {'ge': 0}
241
- and self.use_non_positive_negative_number_constrained_types
242
- ):
232
+ if data_type_kwargs == {"ge": 0} and self.use_non_positive_negative_number_constrained_types:
243
233
  return self.data_type.from_import(IMPORT_NON_NEGATIVE_INT)
244
- if (
245
- data_type_kwargs == {'le': 0}
246
- and self.use_non_positive_negative_number_constrained_types
247
- ):
234
+ if data_type_kwargs == {"le": 0} and self.use_non_positive_negative_number_constrained_types:
248
235
  return self.data_type.from_import(IMPORT_NON_POSITIVE_INT)
249
236
  kwargs = {k: int(v) for k, v in data_type_kwargs.items()}
250
237
  if strict:
251
- kwargs['strict'] = True
238
+ kwargs["strict"] = True
252
239
  return self.data_type.from_import(IMPORT_CONINT, kwargs=kwargs)
253
240
  if strict:
254
241
  return self.strict_type_map[StrictTypes.int]
255
242
  return self.type_map[types]
256
243
 
257
- def get_data_float_type(
244
+ def get_data_float_type( # noqa: PLR0911
258
245
  self,
259
246
  types: Types,
260
247
  **kwargs: Any,
@@ -263,23 +250,17 @@ class DataTypeManager(_DataTypeManager):
263
250
  strict = StrictTypes.float in self.strict_types
264
251
  if data_type_kwargs:
265
252
  if not strict:
266
- if data_type_kwargs == {'gt': 0}:
253
+ if data_type_kwargs == {"gt": 0}:
267
254
  return self.data_type.from_import(IMPORT_POSITIVE_FLOAT)
268
- if data_type_kwargs == {'lt': 0}:
255
+ if data_type_kwargs == {"lt": 0}:
269
256
  return self.data_type.from_import(IMPORT_NEGATIVE_FLOAT)
270
- if (
271
- data_type_kwargs == {'ge': 0}
272
- and self.use_non_positive_negative_number_constrained_types
273
- ):
257
+ if data_type_kwargs == {"ge": 0} and self.use_non_positive_negative_number_constrained_types:
274
258
  return self.data_type.from_import(IMPORT_NON_NEGATIVE_FLOAT)
275
- if (
276
- data_type_kwargs == {'le': 0}
277
- and self.use_non_positive_negative_number_constrained_types
278
- ):
259
+ if data_type_kwargs == {"le": 0} and self.use_non_positive_negative_number_constrained_types:
279
260
  return self.data_type.from_import(IMPORT_NON_POSITIVE_FLOAT)
280
261
  kwargs = {k: float(v) for k, v in data_type_kwargs.items()}
281
262
  if strict:
282
- kwargs['strict'] = True
263
+ kwargs["strict"] = True
283
264
  return self.data_type.from_import(IMPORT_CONFLOAT, kwargs=kwargs)
284
265
  if strict:
285
266
  return self.strict_type_map[StrictTypes.float]
@@ -290,23 +271,18 @@ class DataTypeManager(_DataTypeManager):
290
271
  if data_type_kwargs:
291
272
  return self.data_type.from_import(
292
273
  IMPORT_CONDECIMAL,
293
- kwargs={
294
- k: Decimal(str(v) if isinstance(v, UnionIntFloat) else v)
295
- for k, v in data_type_kwargs.items()
296
- },
274
+ kwargs={k: Decimal(str(v) if isinstance(v, UnionIntFloat) else v) for k, v in data_type_kwargs.items()},
297
275
  )
298
276
  return self.type_map[types]
299
277
 
300
278
  def get_data_str_type(self, types: Types, **kwargs: Any) -> DataType:
301
- data_type_kwargs: Dict[str, Any] = self.transform_kwargs(kwargs, string_kwargs)
279
+ data_type_kwargs: dict[str, Any] = self.transform_kwargs(kwargs, string_kwargs)
302
280
  strict = StrictTypes.str in self.strict_types
303
281
  if data_type_kwargs:
304
282
  if strict:
305
- data_type_kwargs['strict'] = True
283
+ data_type_kwargs["strict"] = True
306
284
  if self.PATTERN_KEY in data_type_kwargs:
307
- escaped_regex = data_type_kwargs[self.PATTERN_KEY].translate(
308
- escape_characters
309
- )
285
+ escaped_regex = data_type_kwargs[self.PATTERN_KEY].translate(escape_characters)
310
286
  # TODO: remove unneeded escaped characters
311
287
  data_type_kwargs[self.PATTERN_KEY] = f"r'{escaped_regex}'"
312
288
  return self.data_type.from_import(IMPORT_CONSTR, kwargs=data_type_kwargs)
@@ -315,39 +291,32 @@ class DataTypeManager(_DataTypeManager):
315
291
  return self.type_map[types]
316
292
 
317
293
  def get_data_bytes_type(self, types: Types, **kwargs: Any) -> DataType:
318
- data_type_kwargs: Dict[str, Any] = self.transform_kwargs(kwargs, byes_kwargs)
294
+ data_type_kwargs: dict[str, Any] = self.transform_kwargs(kwargs, byes_kwargs)
319
295
  strict = StrictTypes.bytes in self.strict_types
320
- if data_type_kwargs:
321
- if not strict:
322
- return self.data_type.from_import(
323
- IMPORT_CONBYTES, kwargs=data_type_kwargs
324
- )
296
+ if data_type_kwargs and not strict:
297
+ return self.data_type.from_import(IMPORT_CONBYTES, kwargs=data_type_kwargs)
325
298
  # conbytes doesn't accept strict argument
326
299
  # https://github.com/samuelcolvin/pydantic/issues/2489
327
- # if strict:
328
- # data_type_kwargs['strict'] = True
329
- # return self.data_type.from_import(IMPORT_CONBYTES, kwargs=data_type_kwargs)
330
300
  if strict:
331
301
  return self.strict_type_map[StrictTypes.bytes]
332
302
  return self.type_map[types]
333
303
 
334
- def get_data_type(
304
+ def get_data_type( # noqa: PLR0911
335
305
  self,
336
306
  types: Types,
337
307
  **kwargs: Any,
338
308
  ) -> DataType:
339
309
  if types == Types.string:
340
310
  return self.get_data_str_type(types, **kwargs)
341
- elif types in (Types.int32, Types.int64, Types.integer):
311
+ if types in {Types.int32, Types.int64, Types.integer}:
342
312
  return self.get_data_int_type(types, **kwargs)
343
- elif types in (Types.float, Types.double, Types.number, Types.time):
313
+ if types in {Types.float, Types.double, Types.number, Types.time}:
344
314
  return self.get_data_float_type(types, **kwargs)
345
- elif types == Types.decimal:
315
+ if types == Types.decimal:
346
316
  return self.get_data_decimal_type(types, **kwargs)
347
- elif types == Types.binary:
317
+ if types == Types.binary:
348
318
  return self.get_data_bytes_type(types, **kwargs)
349
- elif types == Types.boolean:
350
- if StrictTypes.bool in self.strict_types:
351
- return self.strict_type_map[StrictTypes.bool]
319
+ if types == Types.boolean and StrictTypes.bool in self.strict_types:
320
+ return self.strict_type_map[StrictTypes.bool]
352
321
 
353
322
  return self.type_map[types]
@@ -10,27 +10,27 @@ from .types import DataTypeManager
10
10
 
11
11
 
12
12
  def dump_resolve_reference_action(class_names: Iterable[str]) -> str:
13
- return '\n'.join(f'{class_name}.model_rebuild()' for class_name in class_names)
13
+ return "\n".join(f"{class_name}.model_rebuild()" for class_name in class_names)
14
14
 
15
15
 
16
16
  class ConfigDict(_BaseModel):
17
- extra: Optional[str] = None
18
- title: Optional[str] = None
19
- populate_by_name: Optional[bool] = None
20
- allow_extra_fields: Optional[bool] = None
21
- from_attributes: Optional[bool] = None
22
- frozen: Optional[bool] = None
23
- arbitrary_types_allowed: Optional[bool] = None
24
- protected_namespaces: Optional[Tuple[str, ...]] = None
25
- regex_engine: Optional[str] = None
26
- use_enum_values: Optional[bool] = None
17
+ extra: Optional[str] = None # noqa: UP045
18
+ title: Optional[str] = None # noqa: UP045
19
+ populate_by_name: Optional[bool] = None # noqa: UP045
20
+ allow_extra_fields: Optional[bool] = None # noqa: UP045
21
+ from_attributes: Optional[bool] = None # noqa: UP045
22
+ frozen: Optional[bool] = None # noqa: UP045
23
+ arbitrary_types_allowed: Optional[bool] = None # noqa: UP045
24
+ protected_namespaces: Optional[Tuple[str, ...]] = None # noqa: UP006, UP045
25
+ regex_engine: Optional[str] = None # noqa: UP045
26
+ use_enum_values: Optional[bool] = None # noqa: UP045
27
27
 
28
28
 
29
29
  __all__ = [
30
- 'BaseModel',
31
- 'DataModelField',
32
- 'RootModel',
33
- 'dump_resolve_reference_action',
34
- 'DataTypeManager',
35
- 'UnionMode',
30
+ "BaseModel",
31
+ "DataModelField",
32
+ "DataTypeManager",
33
+ "RootModel",
34
+ "UnionMode",
35
+ "dump_resolve_reference_action",
36
36
  ]