From 3dfe7ef8ddb6713b9748a9ebbcb4e73a5bc135a8 Mon Sep 17 00:00:00 2001 From: Tyler Goodlet Date: Fri, 8 Jul 2022 10:54:04 -0400 Subject: [PATCH] Add `Struct.copy()` which does a rountrip validate --- piker/data/types.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/piker/data/types.py b/piker/data/types.py index b7d21680..c6cba61d 100644 --- a/piker/data/types.py +++ b/piker/data/types.py @@ -18,6 +18,7 @@ Built-in (extension) types. """ +from typing import Optional from pprint import pformat import msgspec @@ -43,4 +44,25 @@ class Struct( 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) + )