Skip to content

Commit

Permalink
Add Struct.copy() which does a rountrip validate
Browse files Browse the repository at this point in the history
  • Loading branch information
goodboy committed Jul 9, 2022
1 parent 11b6699 commit c26acb1
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions piker/data/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
Built-in (extension) types.
"""
from typing import Optional
from pprint import pformat

import msgspec
Expand All @@ -43,4 +44,25 @@ def to_dict(self) -> dict:
def __repr__(self):
return f'Struct({pformat(self.to_dict())})'

def copy(
self,
update: Optional[dict] = None,

) -> msgspec.Struct:
'''
Validate-typecast all self defined fields, return a copy of us
with all such fields.
This is kinda like the default behaviour in `pydantic.BaseModel`.
'''
if update:
for k, v in update.items():
setattr(self, k, v)

# roundtrip serialize to validate
return msgspec.msgpack.Decoder(
type=type(self)
).decode(
msgspec.msgpack.Encoder().encode(self)
)

0 comments on commit c26acb1

Please sign in to comment.