Skip to content

Commit 359a8a9

Browse files
authored
Add defaultdict to preserved type origins for TypedDict generation (#2866)
* Add collections types to preserved type origins with dynamic fallback * Add pragma no cover to dynamic collections fallback
1 parent 83776ca commit 359a8a9

1 file changed

Lines changed: 12 additions & 2 deletions

File tree

src/datamodel_code_generator/__main__.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -823,6 +823,7 @@ def _add_python_type_for_unserializable(
823823

824824
def _init_preserved_type_origins() -> dict[type, str]:
825825
"""Initialize preserved type origins mapping (lazy initialization)."""
826+
from collections import ChainMap, Counter, OrderedDict, defaultdict, deque # noqa: PLC0415
826827
from collections.abc import Mapping as ABCMapping # noqa: PLC0415
827828
from collections.abc import MutableMapping as ABCMutableMapping # noqa: PLC0415
828829
from collections.abc import MutableSequence as ABCMutableSequence # noqa: PLC0415
@@ -833,6 +834,11 @@ def _init_preserved_type_origins() -> dict[type, str]:
833834
return {
834835
set: "set",
835836
frozenset: "frozenset",
837+
defaultdict: "defaultdict",
838+
OrderedDict: "OrderedDict",
839+
Counter: "Counter",
840+
deque: "deque",
841+
ChainMap: "ChainMap",
836842
AbstractSet: "AbstractSet",
837843
ABCMutableSet: "MutableSet",
838844
ABCMapping: "Mapping",
@@ -878,8 +884,12 @@ def _serialize_python_type(tp: type) -> str | None:
878884
return " | ".join(n or _simple_type_name(a) for n, a in zip(nested, args, strict=False))
879885
return None # pragma: no cover
880886

881-
if origin in preserved_origins:
882-
type_name = preserved_origins[origin]
887+
type_name: str | None = None
888+
if origin is not None:
889+
type_name = preserved_origins.get(origin)
890+
if type_name is None and getattr(origin, "__module__", None) == "collections": # pragma: no cover
891+
type_name = _simple_type_name(origin)
892+
if type_name is not None:
883893
if args:
884894
args_str = ", ".join(_serialize_python_type(a) or _simple_type_name(a) for a in args)
885895
return f"{type_name}[{args_str}]"

0 commit comments

Comments
 (0)