Skip to content

Commit 8662f5f

Browse files
committed
feat: add serialize flag to dict()
when True, this will avoid unserializable things in the resulting dict, like dates
1 parent 0f3a2ca commit 8662f5f

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

codemeticulous/mixins.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,26 @@
55

66

77
class ByAliasExcludeNoneMixin:
8-
def dict(self):
8+
def dict(self, serialize=False):
9+
"""Return a dictionary representation of the object
10+
11+
If serialize is False, this will include some unserializable objects
12+
like datetimes. If serialize is True, it will return a dictionary that
13+
has been serialized to json and then back
14+
"""
15+
if serialize:
16+
return json.loads(self.json())
917
if hasattr(self, "model_dump"):
1018
return self.model_dump(by_alias=True, exclude_none=True)
1119
return super().dict(by_alias=True, exclude_none=True)
1220

1321
def json(self):
22+
"""return a serialized json string representation of the object"""
1423
if hasattr(self, "model_dump_json"):
1524
return self.model_dump_json(by_alias=True, exclude_none=True)
1625
return super().json(by_alias=True, exclude_none=True)
1726

1827
def yaml(self):
28+
"""return a serialized yaml string representation of the object"""
1929
json_dict = json.loads(self.json())
2030
return yaml.dump(parse_dict_dates(json_dict), sort_keys=False)

0 commit comments

Comments
 (0)