fix: simplify and fix adaptation of models to log entries

This commit is contained in:
gmega 2025-02-20 09:42:23 -03:00
parent 1ab2112542
commit 63501c3b79
No known key found for this signature in database
GPG Key ID: 6290D34EAD824B18
2 changed files with 16 additions and 6 deletions

View File

@ -47,19 +47,19 @@ class LogEntry(SnakeCaseModel):
"""Adapts an existing Pydantic model to a LogEntry. This is useful for when you have a model
that you want to log and later recover from logs using :class:`LogParser` or :class:`LogSplitter`."""
def adapt_instance(cls, data: BaseModel):
return cls.model_validate(data.model_dump())
def adapt_instance(klass, data: BaseModel):
return klass.model_validate(data.model_dump())
def recover_instance(self):
return model.model_validate(self.model_dump())
parents = [base for base in model.__bases__ if issubclass(base, BaseModel)]
adapted = type(
f"{model.__name__}LogEntry",
tuple([LogEntry] + parents),
(
LogEntry,
model,
),
{
"__annotations__": model.__annotations__,
"adapt_instance": classmethod(adapt_instance),
"recover_instance": recover_instance,
},

View File

@ -247,6 +247,9 @@ class AModel(BaseModel):
class BModel(AModel):
b: int
def hello(self):
return f"world {self.a} {self.b}"
def test_should_log_attributes_for_superclasses_in_adapted_entries():
BModelLogEntry = LogEntry.adapt(BModel)
@ -256,3 +259,10 @@ def test_should_log_attributes_for_superclasses_in_adapted_entries():
str(BModelLogEntry.adapt_instance(instance))
== '>>{"a":1,"b":2,"entry_type":"b_model_log_entry"}'
)
def test_should_preserve_methods_in_adapted_entries():
BModelLogEntry = LogEntry.adapt(BModel)
instance = BModel(a=1, b=2)
assert BModelLogEntry.adapt_instance(instance).hello() == "world 1 2"