-
-
Notifications
You must be signed in to change notification settings - Fork 435
Expand file tree
/
Copy pathbase.py
More file actions
3494 lines (3018 loc) · 153 KB
/
base.py
File metadata and controls
3494 lines (3018 loc) · 153 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Abstract base parser and utilities for schema parsing.
Provides the Parser abstract base class that defines the parsing algorithm,
along with helper functions for model sorting, import resolution, and
code generation.
"""
from __future__ import annotations
import builtins
import operator
import os.path
import re
import sys
from abc import ABC, abstractmethod
from collections import Counter, OrderedDict, defaultdict
from collections.abc import Callable, Hashable, Sequence
from itertools import groupby
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
Generic,
NamedTuple,
Optional,
Protocol,
TypeAlias,
TypeVar,
cast,
runtime_checkable,
)
from urllib.parse import ParseResult
from warnings import warn
from pydantic import BaseModel
from typing_extensions import Unpack
from datamodel_code_generator import (
AllExportsCollisionStrategy,
AllExportsScope,
AllOfClassHierarchy,
AllOfMergeMode,
CollapseRootModelsNameStrategy,
Error,
FieldTypeCollisionStrategy,
ModuleSplitMode,
ReadOnlyWriteOnlyModelType,
ReuseScope,
YamlValue,
)
from datamodel_code_generator.format import (
CodeFormatter,
Formatter,
PythonVersion,
resolve_use_type_checking_imports,
)
from datamodel_code_generator.imports import (
IMPORT_ANNOTATIONS,
IMPORT_LITERAL,
IMPORT_OPTIONAL,
IMPORT_UNION,
Import,
Imports,
)
from datamodel_code_generator.model import dataclass as dataclass_model
from datamodel_code_generator.model import msgspec as msgspec_model
from datamodel_code_generator.model import pydantic_v2 as pydantic_model_v2
from datamodel_code_generator.model.base import (
ALL_MODEL,
GENERIC_BASE_CLASS_NAME,
GENERIC_BASE_CLASS_PATH,
UNDEFINED,
BaseClassDataType,
ConstraintsBase,
DataModel,
DataModelFieldBase,
)
from datamodel_code_generator.model.enum import Enum, Member
from datamodel_code_generator.model.type_alias import TypeAliasBase, TypeStatement
from datamodel_code_generator.parser import DefaultPutDict, LiteralType
from datamodel_code_generator.parser._graph import stable_toposort
from datamodel_code_generator.parser._scc import find_circular_sccs, strongly_connected_components
from datamodel_code_generator.reference import ModelResolver, ModelType, Reference
from datamodel_code_generator.types import ANY, DataType, DataTypeManager
from datamodel_code_generator.util import camel_to_snake
if TYPE_CHECKING:
from collections.abc import Iterable, Iterator, Sequence
from datamodel_code_generator._types import ParserConfigDict
from datamodel_code_generator.config import ParserConfig
from datamodel_code_generator.parser.schema_version import JsonSchemaFeatures
ParserConfigT = TypeVar("ParserConfigT", bound="ParserConfig")
SchemaFeaturesT = TypeVar("SchemaFeaturesT", bound="JsonSchemaFeatures")
@runtime_checkable
class HashableComparable(Hashable, Protocol):
"""Protocol for types that are both hashable and support comparison."""
def __lt__(self, value: Any, /) -> bool: ... # noqa: D105
def __le__(self, value: Any, /) -> bool: ... # noqa: D105
def __gt__(self, value: Any, /) -> bool: ... # noqa: D105
def __ge__(self, value: Any, /) -> bool: ... # noqa: D105
ModelName: TypeAlias = str
ModelNames: TypeAlias = set[ModelName]
ModelDeps: TypeAlias = dict[ModelName, set[ModelName]]
OrderIndex: TypeAlias = dict[ModelName, int]
DiscriminatorValue: TypeAlias = str | int | bool
_BUILTIN_NAMES: frozenset[str] = frozenset(name for name in builtins.__dict__ if not name.startswith("_"))
_BUILTIN_NAMES_INTRODUCED_IN: dict[PythonVersion, frozenset[str]] = {
PythonVersion.PY_311: frozenset({"BaseExceptionGroup", "ExceptionGroup"}),
PythonVersion.PY_313: frozenset({"PythonFinalizationError"}),
}
_BUILTIN_CONTAINER_COLLISION_FLAGS: dict[str, str] = {
"list": "is_list",
"dict": "is_dict",
"set": "is_set",
"frozenset": "is_frozen_set",
"tuple": "is_tuple",
}
def _get_builtin_names_for_target(target_python_version: PythonVersion) -> frozenset[str]:
builtin_names = set(_BUILTIN_NAMES)
target_key = target_python_version.version_key
for introduced_version, names in _BUILTIN_NAMES_INTRODUCED_IN.items():
if target_key >= introduced_version.version_key:
builtin_names.update(names)
else:
builtin_names.difference_update(names)
return frozenset(builtin_names)
def _is_builtin_type_collision(current_name: str, data_type: DataType) -> bool:
if data_type.type == current_name and not data_type.import_:
return True
if flag := _BUILTIN_CONTAINER_COLLISION_FLAGS.get(current_name):
return bool(getattr(data_type, flag))
return False
ComponentId: TypeAlias = int
Components: TypeAlias = list[list[ModelName]]
ComponentOf: TypeAlias = dict[ModelName, ComponentId]
ComponentEdges: TypeAlias = dict[ComponentId, set[ComponentId]]
ClassNode: TypeAlias = tuple[ModelName, ...]
ClassGraph: TypeAlias = dict[ClassNode, set[ClassNode]]
ModulePath: TypeAlias = tuple[str, ...]
ModuleModels: TypeAlias = list[tuple[ModulePath, list[DataModel]]]
ForwarderMap: TypeAlias = dict[ModulePath, tuple[ModulePath, list[tuple[str, str]]]]
class ModuleContext(NamedTuple):
"""Context for processing a single module during code generation."""
module: ModulePath
module_key: ModulePath
models: list[DataModel]
is_init: bool
imports: Imports
scoped_model_resolver: ModelResolver
class ParseConfig(NamedTuple):
"""Configuration for the parse operation."""
with_import: bool
use_deferred_annotations: bool
code_formatter: CodeFormatter | None
module_split_mode: ModuleSplitMode | None
all_exports_scope: AllExportsScope | None
all_exports_collision_strategy: AllExportsCollisionStrategy | None
class _KeepModelOrderDeps(NamedTuple):
strong: ModelDeps
all: ModelDeps
class _KeepModelOrderComponents(NamedTuple):
components: Components
comp_of: ComponentOf
def _collect_keep_model_order_deps(
model: DataModel,
*,
model_names: ModelNames,
imported: ModelNames,
use_deferred_annotations: bool,
) -> tuple[set[ModelName], set[ModelName]]:
"""Collect (strong_deps, all_deps) used by keep_model_order sorting.
- strong_deps: base class references (within-module, non-imported)
- all_deps: base class refs + (optionally) field refs (within-module, non-imported)
"""
class_name = model.class_name
base_class_refs = {b.reference.short_name for b in model.base_classes if b.reference}
field_refs = {t.reference.short_name for f in model.fields for t in f.data_type.all_data_types if t.reference}
if use_deferred_annotations and not isinstance(model, (TypeAliasBase, pydantic_model_v2.RootModel)):
field_refs = set()
strong = {r for r in base_class_refs if r in model_names and r not in imported and r != class_name}
deps = {r for r in (base_class_refs | field_refs) if r in model_names and r not in imported and r != class_name}
return strong, deps
def _build_keep_model_order_dependency_maps(
models: list[DataModel],
*,
model_names: ModelNames,
imported: ModelNames,
use_deferred_annotations: bool,
) -> _KeepModelOrderDeps:
strong_deps: ModelDeps = {}
all_deps: ModelDeps = {}
for model in models:
strong, deps = _collect_keep_model_order_deps(
model,
model_names=model_names,
imported=imported,
use_deferred_annotations=use_deferred_annotations,
)
strong_deps[model.class_name] = strong
all_deps[model.class_name] = deps
return _KeepModelOrderDeps(strong=strong_deps, all=all_deps)
def _build_keep_model_order_components(
all_deps: ModelDeps,
order_index: OrderIndex,
) -> _KeepModelOrderComponents:
graph: ClassGraph = {(name,): {(dep,) for dep in deps} for name, deps in all_deps.items()}
sccs = strongly_connected_components(graph)
components: Components = [sorted((node[0] for node in scc), key=order_index.__getitem__) for scc in sccs]
components.sort(key=lambda members: min(order_index[n] for n in members))
comp_of: ComponentOf = {name: i for i, members in enumerate(components) for name in members}
return _KeepModelOrderComponents(components=components, comp_of=comp_of)
def _build_keep_model_order_component_edges(
all_deps: ModelDeps,
comp_of: ComponentOf,
num_components: int,
) -> ComponentEdges:
comp_edges: ComponentEdges = {i: set() for i in range(num_components)}
for name, deps in all_deps.items():
name_comp = comp_of[name]
for dep in deps:
if (dep_comp := comp_of[dep]) != name_comp:
comp_edges[dep_comp].add(name_comp)
return comp_edges
def _build_keep_model_order_component_order(
components: Components,
comp_edges: ComponentEdges,
order_index: OrderIndex,
) -> list[ComponentId]:
comp_key = [min(order_index[n] for n in members) for members in components]
return stable_toposort(
list(range(len(components))),
comp_edges,
key=lambda component_id: comp_key[component_id],
)
def _build_keep_model_ordered_names(
ordered_comp_ids: list[ComponentId],
components: Components,
strong_deps: ModelDeps,
order_index: OrderIndex,
) -> list[ModelName]:
ordered_names: list[ModelName] = []
for component_id in ordered_comp_ids:
members = components[component_id]
if len(members) > 1:
strong_edges: dict[ModelName, set[ModelName]] = {n: set() for n in members}
member_set = set(members)
for base in members:
derived_members = {member for member in members if base in strong_deps.get(member, set()) & member_set}
strong_edges[base].update(derived_members)
members = stable_toposort(members, strong_edges, key=order_index.__getitem__)
ordered_names.extend(members)
return ordered_names
def _reorder_models_keep_model_order(
models: list[DataModel],
imports: Imports,
*,
use_deferred_annotations: bool,
) -> None:
"""Reorder models deterministically based on their dependencies.
Starts from class_name order and only moves models when required to satisfy dependencies.
Cycles are kept as SCC groups; within each SCC, base-class dependencies are prioritized.
"""
models.sort(key=lambda x: x.class_name)
imported: ModelNames = {i for v in imports.values() for i in v}
model_by_name = {m.class_name: m for m in models}
model_names: ModelNames = set(model_by_name)
order_index: OrderIndex = {m.class_name: i for i, m in enumerate(models)}
deps = _build_keep_model_order_dependency_maps(
models,
model_names=model_names,
imported=imported,
use_deferred_annotations=use_deferred_annotations,
)
comps = _build_keep_model_order_components(deps.all, order_index)
comp_edges = _build_keep_model_order_component_edges(deps.all, comps.comp_of, len(comps.components))
ordered_comp_ids = _build_keep_model_order_component_order(comps.components, comp_edges, order_index)
ordered_names = _build_keep_model_ordered_names(ordered_comp_ids, comps.components, deps.strong, order_index)
models[:] = [model_by_name[name] for name in ordered_names]
SPECIAL_PATH_FORMAT: str = "#-datamodel-code-generator-#-{}-#-special-#"
def get_special_path(keyword: str, path: list[str]) -> list[str]:
"""Create a special path marker for internal reference tracking."""
return [*path, SPECIAL_PATH_FORMAT.format(keyword)]
escape_characters = str.maketrans({
"\u0000": r"\x00", # Null byte
"\\": r"\\",
"'": r"\'",
"\b": r"\b",
"\f": r"\f",
"\n": r"\n",
"\r": r"\r",
"\t": r"\t",
})
def to_hashable(item: Any) -> HashableComparable: # noqa: PLR0911
"""Convert an item to a hashable and comparable representation.
Returns a value that is both hashable and supports comparison operators.
Used for caching and deduplication of models.
"""
if isinstance(
item,
(
list,
tuple,
),
):
try:
return tuple(sorted((to_hashable(i) for i in item), key=lambda v: (str(type(v)), v)))
except TypeError:
# Fallback when mixed, non-comparable types are present; preserve original order
return tuple(to_hashable(i) for i in item)
if isinstance(item, dict):
return tuple(
sorted(
(
k,
to_hashable(v),
)
for k, v in item.items()
)
)
if isinstance(item, set): # pragma: no cover
return frozenset(to_hashable(i) for i in item) # type: ignore[return-value]
if isinstance(item, BaseModel): # pragma: no cover
return to_hashable(item.model_dump())
if item is None:
return ""
return item # type: ignore[return-value]
def dump_templates(templates: list[DataModel]) -> str:
"""Join model templates into a single code string."""
return "\n\n\n".join(str(m) for m in templates)
def iter_models_field_data_types(
models: Iterable[DataModel],
) -> Iterator[tuple[DataModel, DataModelFieldBase, DataType]]:
"""Yield (model, field, data_type) for all models, fields, and nested data types."""
for model in models:
for field in model.fields:
for data_type in field.data_type.all_data_types:
yield model, field, data_type
def _unwrap_type_alias(data_type: DataType) -> DataType:
"""Follow type alias references to the underlying data type."""
current = data_type
seen: set[int] = set()
while current.reference and isinstance(current.reference.source, TypeAliasBase):
source = current.reference.source
if id(source) in seen or not source.fields:
break
seen.add(id(source))
current = source.fields[0].data_type
return current
def _contains_model_reference(data_type: DataType) -> bool:
"""Check if a data type tree contains any reference to a non-alias model."""
stack = [data_type]
seen: set[int] = set()
while stack:
resolved = _unwrap_type_alias(stack.pop())
resolved_id = id(resolved)
if resolved_id in seen:
continue
seen.add(resolved_id)
if (
resolved.reference
and isinstance(resolved.reference.source, DataModel)
and not isinstance(resolved.reference.source, Enum)
and not resolved.reference.source.is_alias
):
return True
if resolved.dict_key:
stack.append(resolved.dict_key)
stack.extend(resolved.data_types)
return False
def _needs_validate_default(data_type: DataType) -> bool:
"""Check if a field needs validate_default=True to coerce defaults into model instances."""
resolved = _unwrap_type_alias(data_type)
return _contains_model_reference(resolved)
def _alias_base_class_imports(
model: DataModel,
aliased_imports: dict[tuple[str | None, str], Import],
) -> None:
"""Apply aliased imports to a model's base classes and their _additional_imports."""
for base_class in model.base_classes:
if not base_class.import_:
continue
key = (base_class.import_.from_, base_class.import_.import_)
if key not in aliased_imports:
continue
old_import = base_class.import_
aliased_import = aliased_imports[key]
base_class.type = aliased_import.alias # type: ignore[assignment]
base_class.import_ = aliased_import
for i, additional_import in enumerate(model._additional_imports): # pragma: no branch # noqa: SLF001
if (
additional_import.from_ == old_import.from_ and additional_import.import_ == old_import.import_
): # pragma: no branch
model._additional_imports[i] = aliased_import # noqa: SLF001
break
ReferenceMapSet = dict[str, set[str]]
SortedDataModels = dict[str, DataModel]
MAX_RECURSION_COUNT: int = sys.getrecursionlimit()
def add_model_path_to_list(
paths: list[str] | None,
model: DataModel,
/,
) -> list[str]:
"""
Auxiliary method which adds model path to list, provided the following hold.
- model is not a type alias
- path is not already in the list.
"""
if paths is None:
paths = []
if model.is_alias:
return paths
if (path := model.path) in paths:
return paths
paths.append(path)
return paths
def sort_data_models( # noqa: PLR0912, PLR0914, PLR0915
unsorted_data_models: list[DataModel],
sorted_data_models: SortedDataModels | None = None,
require_update_action_models: list[str] | None = None,
recursion_count: int = MAX_RECURSION_COUNT,
) -> tuple[list[DataModel], SortedDataModels, list[str]]:
"""Sort data models by dependency order for correct forward references."""
if sorted_data_models is None:
sorted_data_models = OrderedDict()
if require_update_action_models is None:
require_update_action_models = []
sorted_model_count: int = len(sorted_data_models)
unresolved_references: list[DataModel] = []
for model in unsorted_data_models:
if not model.reference_classes:
sorted_data_models[model.path] = model
elif model.path in model.reference_classes and len(model.reference_classes) == 1: # only self-referencing
sorted_data_models[model.path] = model
add_model_path_to_list(require_update_action_models, model)
elif (
not model.reference_classes - {model.path} - sorted_data_models.keys()
): # reference classes have been resolved
sorted_data_models[model.path] = model
if model.path in model.reference_classes:
add_model_path_to_list(require_update_action_models, model)
else:
unresolved_references.append(model)
if unresolved_references:
if sorted_model_count != len(sorted_data_models) and recursion_count:
try:
return sort_data_models(
unresolved_references,
sorted_data_models,
require_update_action_models,
recursion_count - 1,
)
except RecursionError: # pragma: no cover
pass
# sort on base_class dependency
seen_orderings: set[tuple[str, ...]] = set()
while True:
ordered_models: list[tuple[int, DataModel]] = []
# Build lookup dict for O(1) index access instead of O(n) list.index()
path_to_index = {m.path: idx for idx, m in enumerate(unresolved_references)}
for model in unresolved_references:
if isinstance(model, pydantic_model_v2.RootModel):
indexes = [
path_to_index[ref_path]
for f in model.fields
for t in f.data_type.all_data_types
if t.reference and (ref_path := t.reference.path) in path_to_index
]
else:
indexes = [
path_to_index[b.reference.path]
for b in model.base_classes
if b.reference and b.reference.path in path_to_index
]
if indexes:
ordered_models.append((
max(indexes),
model,
))
else:
ordered_models.append((
-1,
model,
))
sorted_unresolved_models = [m[1] for m in sorted(ordered_models, key=operator.itemgetter(0))]
if sorted_unresolved_models == unresolved_references:
break
sig = tuple(m.path for m in sorted_unresolved_models)
if sig in seen_orderings:
# Base-class dependency order has no fixed point (e.g. cyclic inheritance with
# discriminators). Further iterations only permute the list; use stable order.
unresolved_references.sort(key=lambda m: m.path)
break
seen_orderings.add(sig)
unresolved_references = sorted_unresolved_models
# circular reference
unsorted_data_model_names = set(path_to_index.keys())
for model in unresolved_references:
unresolved_model = model.reference_classes - {model.path} - sorted_data_models.keys()
base_models = [getattr(s.reference, "path", None) for s in model.base_classes]
update_action_parent = set(require_update_action_models).intersection(base_models)
if not unresolved_model:
sorted_data_models[model.path] = model
if update_action_parent:
add_model_path_to_list(require_update_action_models, model)
continue
if not unresolved_model - unsorted_data_model_names:
sorted_data_models[model.path] = model
add_model_path_to_list(require_update_action_models, model)
continue
# unresolved
unresolved_classes = ", ".join(
f"[class: {item.path} references: {item.reference_classes}]" for item in unresolved_references
)
msg = f"A Parser can not resolve classes: {unresolved_classes}."
raise Exception(msg) # noqa: TRY002
return unresolved_references, sorted_data_models, require_update_action_models
def sort_base_classes_for_mro(sorted_data_models: SortedDataModels) -> None:
"""Sort base classes in each model to ensure valid Python MRO.
When a class inherits from multiple base classes where some bases inherit
from others, Python's C3 linearization requires that child classes appear
before their parent classes in the inheritance list.
For example, if B inherits from A, then class C(A, B) is invalid but
class C(B, A) is valid.
"""
for model in sorted_data_models.values():
base_classes = model.base_classes
if len(base_classes) <= 1:
continue
# Build set of base class paths for quick lookup
base_class_paths = {b.reference.path for b in base_classes if b.reference}
def get_ancestors(
ref_path: str,
base_class_paths: set[str] = base_class_paths,
) -> set[str]:
"""Get all ancestor paths that are in our base class list."""
ancestors: set[str] = set()
source_model = sorted_data_models.get(ref_path)
if source_model is None: # pragma: no cover
return ancestors
to_visit = [
bc.reference.path
for bc in source_model.base_classes
if bc.reference and bc.reference.path in base_class_paths
]
while to_visit:
parent_path = to_visit.pop()
if parent_path in ancestors:
continue
ancestors.add(parent_path)
parent_model = sorted_data_models.get(parent_path)
if not parent_model: # pragma: no cover
continue
to_visit.extend(
bc.reference.path
for bc in parent_model.base_classes
if bc.reference and bc.reference.path in base_class_paths
)
return ancestors
# Build ancestor map for each base class
ancestor_map = {b.reference.path: get_ancestors(b.reference.path) for b in base_classes if b.reference}
def sort_key(
bc: BaseClassDataType,
ancestor_map: dict[str, set[str]] = ancestor_map,
) -> int:
"""Sort key: classes that are ancestors of others come later."""
if not bc.reference:
return 0
path = bc.reference.path
# Count how many other base classes have this one as an ancestor
return sum(1 for other_path in ancestor_map if path in ancestor_map.get(other_path, set()))
# Use stable sort to preserve original order for elements with equal keys
model.base_classes = sorted(base_classes, key=sort_key)
def relative(
current_module: str,
reference: str,
*,
reference_is_module: bool = False,
current_is_init: bool = False,
) -> tuple[str, str]:
"""Find relative module path.
Args:
current_module: Current module path (e.g., "foo.bar")
reference: Reference path (e.g., "foo.baz.ClassName" or "foo.baz" if reference_is_module)
reference_is_module: If True, treat reference as a module path (not module.class)
current_is_init: If True, treat current_module as a package __init__.py (adds depth)
Returns:
Tuple of (from_path, import_name) for constructing import statements
"""
if current_is_init:
current_module_path = [*current_module.split("."), "__init__"] if current_module else ["__init__"]
else:
current_module_path = current_module.split(".") if current_module else []
if reference_is_module:
reference_path = reference.split(".") if reference else []
name = reference_path[-1] if reference_path else ""
else:
*reference_path, name = reference.split(".")
if current_module_path == reference_path:
return "", ""
i = 0
for x, y in zip(current_module_path, reference_path, strict=False):
if x != y:
break
i += 1
left = "." * (len(current_module_path) - i)
right = ".".join(reference_path[i:])
if not left:
left = "."
if not right:
right = name
elif "." in right:
extra, right = right.rsplit(".", 1)
left += extra
return left, right
def is_ancestor_package_reference(current_module: str, reference: str) -> bool:
"""Check if reference is in an ancestor package (__init__.py).
When the reference's module path is an ancestor (prefix) of the current module,
the reference is in an ancestor package's __init__.py file.
Args:
current_module: The current module path (e.g., "v0.mammal.canine")
reference: The full reference path (e.g., "v0.Animal")
Returns:
True if the reference is in an ancestor package, False otherwise.
Examples:
- current="v0.animal", ref="v0.Animal" -> True (immediate parent)
- current="v0.mammal.canine", ref="v0.Animal" -> True (grandparent)
- current="v0.animal", ref="v0.animal.Dog" -> False (same or child)
- current="pets", ref="Animal" -> True (root package is immediate parent)
"""
current_path = current_module.split(".") if current_module else []
*reference_path, _ = reference.split(".")
if not current_path:
return False
# Case 1: Direct parent package (includes root package when reference_path is empty)
# e.g., current="pets", ref="Animal" -> current_path[:-1]=[] == reference_path=[]
if current_path[:-1] == reference_path:
return True
# Case 2: Deeper ancestor package (reference_path must be non-empty proper prefix)
# e.g., current="v0.mammal.canine", ref="v0.Animal" -> ["v0"] is prefix of ["v0","mammal","canine"]
return (
len(reference_path) > 0
and len(reference_path) < len(current_path)
and current_path[: len(reference_path)] == reference_path
)
def exact_import(from_: str, import_: str, short_name: str) -> tuple[str, str]:
"""Create exact import path to avoid relative import issues."""
if from_ == len(from_) * ".":
# Prevents "from . import foo" becoming "from ..foo import Foo"
# or "from .. import foo" becoming "from ...foo import Foo"
# when our imported module has the same parent
return f"{from_}{import_}", short_name
return f"{from_}.{import_}", short_name
def get_module_directory(module: tuple[str, ...]) -> tuple[str, ...]:
"""Get the directory portion of a module tuple.
Note: Module tuples in module_models do NOT include .py extension.
The last element is either the module name (e.g., "issuing") or empty for root.
Examples:
("pkg",) -> ("pkg",) - root module
("pkg", "issuing") -> ("pkg",) - submodule
("foo", "bar", "baz") -> ("foo", "bar") - deeply nested module
"""
if not module:
return ()
if len(module) == 1:
return module
return module[:-1]
@runtime_checkable
class Child(Protocol):
"""Protocol for objects with a parent reference."""
@property
def parent(self) -> Any | None:
"""Get the parent object reference."""
raise NotImplementedError
T = TypeVar("T")
def get_most_of_parent(value: Any, type_: type[T] | None = None) -> T | None:
"""Traverse parent chain to find the outermost matching parent."""
if isinstance(value, Child) and (type_ is None or not isinstance(value, type_)):
return get_most_of_parent(value.parent, type_)
return value
def title_to_class_name(title: str) -> str:
"""Convert a schema title to a valid Python class name."""
classname = re.sub(r"[^A-Za-z0-9]+", " ", title)
return "".join(x for x in classname.title() if not x.isspace())
def _find_base_classes(model: DataModel) -> list[DataModel]:
"""Get direct base class DataModels."""
return [b.reference.source for b in model.base_classes if b.reference and isinstance(b.reference.source, DataModel)]
def _find_field(original_name: str, models: list[DataModel]) -> DataModelFieldBase | None:
"""Find a field by original_name in the models and their base classes."""
for model in models:
for field in model.iter_all_fields(): # pragma: no cover
if field.original_name == original_name:
return field
return None # pragma: no cover
def _copy_data_types(data_types: list[DataType]) -> list[DataType]:
"""Deep copy a list of DataType objects, preserving references."""
copied_data_types: list[DataType] = []
for data_type_ in data_types:
if data_type_.reference:
copied_data_types.append(data_type_.__class__(reference=data_type_.reference))
elif data_type_.data_types: # pragma: no cover
copied_data_type = data_type_.model_copy()
copied_data_type.data_types = _copy_data_types(data_type_.data_types)
copied_data_types.append(copied_data_type)
else:
copied_data_types.append(data_type_.model_copy())
return copied_data_types
class Result(BaseModel):
"""Generated code result with optional source file reference."""
body: str
future_imports: str = ""
source: Optional[Path] = None # noqa: UP045
class Source(BaseModel):
"""Schema source file with path and content."""
path: Path
text: str = ""
raw_data: dict[str, YamlValue] | None = None
@classmethod
def from_path(cls, path: Path, base_path: Path, encoding: str) -> Source:
"""Create a Source from a file path relative to base_path."""
return cls(
path=path.relative_to(base_path),
text=path.read_text(encoding=encoding),
)
@classmethod
def from_dict(cls, data: dict[str, YamlValue]) -> Source:
"""Create a Source from a dict."""
return cls(path=Path(), raw_data=data)
class Parser(ABC, Generic[ParserConfigT, SchemaFeaturesT]):
"""Abstract base class for schema parsers.
Provides the parsing algorithm and code generation. Subclasses implement
parse_raw() to handle specific schema formats.
Type Parameters:
ParserConfigT: The configuration type for this parser.
SchemaFeaturesT: The schema features type (JsonSchemaFeatures or subclass).
"""
@property
@abstractmethod
def schema_features(self) -> SchemaFeaturesT:
"""Get schema features based on detected version.
Returns:
Schema features instance with version-specific flags.
"""
...
_config_class_name: ClassVar[str] = "ParserConfig"
@classmethod
def _get_config_class(cls) -> type[ParserConfig]:
"""Return the config class for this parser.
Uses _config_class_name class variable to dynamically import the config class.
Subclasses should set _config_class_name to their config class name.
"""
import importlib # noqa: PLC0415
module = importlib.import_module("datamodel_code_generator.config")
return getattr(module, cls._config_class_name)
@classmethod
def _create_default_config(cls, options: ParserConfigDict) -> ParserConfigT: # ty: ignore
"""Create a default config from options.
Uses _get_config_class() to determine which config class to instantiate.
"""
from datamodel_code_generator import types as types_module # noqa: PLC0415
from datamodel_code_generator.model import base as model_base # noqa: PLC0415
config_class = cls._get_config_class()
config_class.model_rebuild(
_types_namespace={
"StrictTypes": types_module.StrictTypes,
"DataModel": model_base.DataModel,
"DataModelFieldBase": model_base.DataModelFieldBase,
"DataTypeManager": types_module.DataTypeManager,
}
)
return config_class.model_validate(options) # type: ignore[return-value]
def __init__( # noqa: PLR0912, PLR0915
self,
source: str | Path | list[Path] | ParseResult | dict[str, YamlValue],
*,
config: ParserConfigT | None = None,
**options: Unpack[ParserConfigDict],
) -> None:
"""Initialize the Parser with configuration options.
Args:
source: The schema source to parse.
config: Optional ParserConfig object with all configuration options.
**options: Individual configuration options (alternative to config).
Raises:
ValueError: If both config and **options are provided.
"""
if config is not None and options:
msg = "Cannot specify both 'config' and keyword arguments. Use one or the other."
raise ValueError(msg)
if config is None:
config = self._create_default_config(options) # ty: ignore
self.config = config
self.keyword_only = config.keyword_only
self.target_pydantic_version = config.target_pydantic_version
self.frozen_dataclasses = config.frozen_dataclasses
self.data_type_manager: DataTypeManager = config.data_type_manager_type(
python_version=config.target_python_version,
use_standard_collections=config.use_standard_collections,
use_generic_container_types=config.use_generic_container_types,
use_non_positive_negative_number_constrained_types=config.use_non_positive_negative_number_constrained_types,
use_decimal_for_multiple_of=config.use_decimal_for_multiple_of,
strict_types=config.strict_types,
use_union_operator=config.use_union_operator,
use_pendulum=config.use_pendulum,
use_standard_primitive_types=config.use_standard_primitive_types,
target_datetime_class=config.target_datetime_class,
target_date_class=config.target_date_class,
treat_dot_as_module=config.treat_dot_as_module or False,
use_serialize_as_any=config.use_serialize_as_any,
)
self.data_model_type: type[DataModel] = config.data_model_type
self.data_model_root_type: type[DataModel] = config.data_model_root_type
self.data_model_field_type: type[DataModelFieldBase] = config.data_model_field_type
self.imports: Imports = Imports(config.use_exact_imports)
self.use_exact_imports: bool = config.use_exact_imports
self.use_type_checking_imports: bool | None = config.use_type_checking_imports
self._append_additional_imports(additional_imports=config.additional_imports)
self.class_decorators: list[str] = config.class_decorators or []
self.base_class: str | None = config.base_class
self.base_class_map: dict[str, str | list[str]] | None = config.base_class_map
self.target_python_version: PythonVersion = config.target_python_version
self.builtin_names: frozenset[str] = _get_builtin_names_for_target(self.target_python_version)
self.results: list[DataModel] = []
self.dump_resolve_reference_action: Callable[[Iterable[str]], str] | None = config.dump_resolve_reference_action
self.validation: bool = config.validation
self.field_constraints: bool = config.field_constraints
self.snake_case_field: bool = config.snake_case_field
self.strip_default_none: bool = config.strip_default_none
self.apply_default_values_for_required_fields: bool = config.apply_default_values_for_required_fields