Skip to content

Commit

Permalink
fix: nested Codec classes
Browse files Browse the repository at this point in the history
  • Loading branch information
zshipko committed Sep 25, 2024
1 parent 6a05326 commit 2f8a6ed
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions lib/src/prelude.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
class Codec(ABC):
"""
Codec is used to serialize and deserialize values in Extism memory
"""
"""

@abstractmethod
def encode(self) -> bytes:
Expand All @@ -38,6 +38,24 @@ def decode(s: bytes):
"""Decode a value from bytes"""
raise Exception("encode not implemented")

def _fix_fields(self):
if not hasattr(self, '__dict__'):
return
types = self.__annotations__
for k, v in self.__dict__.items():
if k in types:
setattr(self, k, self._fix_field(types[k], k, v))
return self

def _fix_field(self, ty: type, k, v):
try:
if isinstance(v, dict) and issubclass(ty, Codec):
return ty(**v)._fix_fields()
except Exception as _:
pass

return v


class JSONEncoder(json.JSONEncoder):
def default(self, o):
Expand Down Expand Up @@ -84,7 +102,7 @@ def encode(self) -> bytes:
@classmethod
def decode(cls, s: bytes):
x = json.loads(s.decode(), cls=JSONDecoder)
return cls(**x)
return cls(**x)._fix_fields()


class JsonObject(Json, dict):
Expand Down

0 comments on commit 2f8a6ed

Please sign in to comment.