Replies: 1 comment 1 reply
-
|
The problem is that the serialization function is determined by the suffix. so you can store the type info in the suffix: class MyFormat:
def __init__(self,typ):
self.suffix=f".{typ.__name__}"
self.typ=typ
def is_format_for(self,value):
return isinstance(value,self.typ)
def encode(self,value,path:Path):
path.write_text(MessageToJson(value))
def decode(self,path:Path):
return Parse(path.read_text(),self.typ)
for typ in (TypeA,TypeB): # register all types
register_format(MyFormat(typ))or in the data: @register_format
class DynamicFormat:
suffix=".dyn"
def is_format_for(self,value):
# maybe you have some way to check this
# you can also use:
# assert value == external(".dyn")
# in your code
def encode(self,value,path:Path):
typ=type(value)
data=json.loads(MessageToJson(value))
path.write_text(json.dumps({"type":typ.__qualname__,data:value}))
def decode(self,path:Path):
data=json.loads(path.read_text())
typ_name=data["type"]
typ=use_importlib_to_import_your_type_by_name(type_name)
return Parse(json.dumps(data["data"]),typ)I have not tested this code. Let me know when you have problems or questions. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
I currently use
inline-snapshotfor testing a GRPC service, where many test inputs and outputs are stored in external files due to size. The nature of protobuf makes the serde functions the same, albeit with different Message types. If I were to use @register_format, I would need to create a format for each type, which is less ideal compared to creating a "dynamic type" format that can resolve into any protobuf message the same way. This also extends to custom pydantic BaseModels or stdlib dataclasses.I currently get around this with the following code:
This could be possible via
@register_formatif registered formats have some way of taking kwargs, etc.Beta Was this translation helpful? Give feedback.
All reactions