Skip to content

Commit 76027aa

Browse files
committed
feat: exclude defaults and none
1 parent e655859 commit 76027aa

File tree

4 files changed

+108
-18
lines changed

4 files changed

+108
-18
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
"""
2+
{{#description}}{{{description}}}{{/description}}{{^description}}{{{classname}}}{{/description}}
3+
"""

templates/python/model_enum.mustache

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
class {{classname}}({{vendorExtensions.x-py-enum-type}}, Enum):
2-
"""
3-
{{{description}}}{{^description}}{{{classname}}}{{/description}}
4-
"""
2+
{{>model_description}}
3+
54
{{#allowableValues}}
65
{{#enumVars}}
76
{{{name}}} = {{{value}}}
87
{{/enumVars}}
98

109
@classmethod
11-
def from_json(cls, json_str: str) -> Self:
12-
"""Create an instance of {{classname}} from a JSON string"""
13-
return cls(json.loads(json_str))
10+
def from_json(cls, raw_str: str) -> Self:
11+
"""Create an instance of {{classname}} from a string"""
12+
return cls(raw_str)
1413
{{/allowableValues}}

templates/python/model_generic.mustache

Lines changed: 94 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}):
2-
"""
3-
{{#description}}{{{description}}}{{/description}}{{^description}}{{{classname}}}{{/description}}
4-
"""
2+
{{>model_description}}
3+
54
{{#vars}}
65
{{name}}: {{{vendorExtensions.x-py-typing}}}
76
{{/vars}}
@@ -62,14 +61,15 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
6261
{{/vars}}
6362

6463
model_config = ConfigDict(
64+
use_enum_values=True,
6565
populate_by_name=True,
6666
validate_assignment=True,
6767
protected_namespaces=(),
6868
)
6969

7070
def to_str(self) -> str:
7171
"""Returns the string representation of the model using alias"""
72-
return pprint.pformat(self.model_dump(by_alias=True))
72+
return pprint.pformat(self.model_dump(by_alias=True, exclude_unset=True, exclude_defaults=True))
7373

7474
def to_json(self) -> str:
7575
"""Returns the JSON representation of the model using alias"""
@@ -81,7 +81,96 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
8181
return cls.from_dict(json.loads(json_str))
8282

8383
def to_dict(self) -> Dict[str, Any]:
84-
return self.model_dump(by_alias=True)
84+
"""Return the dictionary representation of the model using alias.
85+
86+
This is the same as `self.mode_dump` from Pydantic, except that we only add to the output dict for nullable fields that were set at model initialization. Other fields with value `None` are ignored
87+
"""
88+
_dict = self.model_dump(
89+
by_alias=True,
90+
exclude_unset=True,
91+
exclude_defaults=True,
92+
exclude_none=True,
93+
exclude={
94+
{{#vendorExtensions.x-py-readonly}}
95+
"{{{.}}}",
96+
{{/vendorExtensions.x-py-readonly}}
97+
{{#isAdditionalPropertiesTrue}}
98+
"additional_properties",
99+
{{/isAdditionalPropertiesTrue}}
100+
},
101+
)
102+
{{#allVars}}
103+
{{#isContainer}}
104+
{{#isArray}}
105+
{{#items.isArray}}
106+
{{^items.items.isPrimitiveType}}
107+
_items = []
108+
if self.{{{name}}}:
109+
for _item in self.{{{name}}}:
110+
if _item:
111+
_items.append(
112+
[_inner_item.to_dict() for _inner_item in _item if _inner_item is not None]
113+
)
114+
_dict['{{{baseName}}}'] = _items
115+
{{/items.items.isPrimitiveType}}
116+
{{/items.isArray}}
117+
{{^items.isArray}}
118+
{{^items.isPrimitiveType}}
119+
{{^items.isEnumOrRef}}
120+
_items = []
121+
if self.{{{name}}}:
122+
for _item in self.{{{name}}}:
123+
if _item:
124+
_items.append(_item.to_dict())
125+
_dict['{{{baseName}}}'] = _items
126+
{{/items.isEnumOrRef}}
127+
{{/items.isPrimitiveType}}
128+
{{/items.isArray}}
129+
{{/isArray}}
130+
{{#isMap}}
131+
{{#items.isArray}}
132+
{{^items.items.isPrimitiveType}}
133+
_field_dict_of_array = {}
134+
if self.{{{name}}}:
135+
for _key in self.{{{name}}}:
136+
if self.{{{name}}}[_key] is not None:
137+
_field_dict_of_array[_key] = [
138+
_item.to_dict() for _item in self.{{{name}}}[_key]
139+
]
140+
_dict['{{{baseName}}}'] = _field_dict_of_array
141+
{{/items.items.isPrimitiveType}}
142+
{{/items.isArray}}
143+
{{^items.isArray}}
144+
{{^items.isPrimitiveType}}
145+
{{^items.isEnumOrRef}}
146+
_field_dict = {}
147+
if self.{{{name}}}:
148+
for _key in self.{{{name}}}:
149+
if self.{{{name}}}[_key]:
150+
_field_dict[_key] = self.{{{name}}}[_key].to_dict()
151+
_dict['{{{baseName}}}'] = _field_dict
152+
{{/items.isEnumOrRef}}
153+
{{/items.isPrimitiveType}}
154+
{{/items.isArray}}
155+
{{/isMap}}
156+
{{/isContainer}}
157+
{{^isContainer}}
158+
{{^isPrimitiveType}}
159+
{{^isEnumOrRef}}
160+
if self.{{{name}}}:
161+
_dict['{{{baseName}}}'] = self.{{{name}}}.to_dict()
162+
{{/isEnumOrRef}}
163+
{{/isPrimitiveType}}
164+
{{/isContainer}}
165+
{{/allVars}}
166+
{{#isAdditionalPropertiesTrue}}
167+
# puts key-value pairs in additional_properties in the top level
168+
if self.additional_properties is not None:
169+
for _key, _value in self.additional_properties.items():
170+
_dict[_key] = _value
171+
172+
{{/isAdditionalPropertiesTrue}}
173+
return _dict
85174

86175
@classmethod
87176
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:

templates/python/model_oneof.mustache

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}):
2-
"""
3-
{{{description}}}{{^description}}{{{classname}}}{{/description}}
4-
"""
2+
{{>model_description}}
53

64
@staticmethod
75
def model_discriminator(v: Any) -> Optional[str]:
@@ -23,6 +21,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
2321
]] = None
2422

2523
model_config = ConfigDict(
24+
use_enum_values=True,
2625
validate_assignment=True,
2726
protected_namespaces=(),
2827
)
@@ -76,7 +75,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
7675
raise ValueError("No match found when deserializing the JSON string into {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages))
7776

7877
def to_json(self) -> str:
79-
"""Returns the JSON representation of the actual instance"""
78+
"""Returns the JSON representation of the one_of value"""
8079
if self.value is None:
8180
return "null"
8281
if hasattr(self.value, "to_json") and callable(self.value.to_json):
@@ -85,7 +84,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
8584
return json.dumps(self.value)
8685

8786
def to_dict(self) -> Optional[Union[Dict[str, Any], {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}]]:
88-
"""Returns the dict representation of the actual instance"""
87+
"""Returns the dict representation of the one_of value"""
8988
if self.value is None:
9089
return None
9190
if hasattr(self.value, "to_dict") and callable(self.value.to_dict):
@@ -94,5 +93,5 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
9493
return self.value
9594

9695
def to_str(self) -> str:
97-
"""Returns the string representation of the actual instance"""
98-
return pprint.pformat(self.model_dump())
96+
"""Returns the string representation of the one_of value"""
97+
return pprint.pformat(self.model_dump(by_alias=True, exclude_unset=True, exclude_defaults=True))

0 commit comments

Comments
 (0)