You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
From comments in #558. Custom metamethods and make_unstructure_dict_unstructure_fn cannot be used together:
importcattrsfromcattrs.strategiesimportuse_class_methodsimportattrs# Use a set of metamethods@attrs.defineclassThing:
a: intdef_unstructure(self):
return {"a" : str(self.a)}
@classmethoddef_structure(cls, val):
returncls(a=int(val["a"]))
conv=cattrs.Converter()
use_class_methods(
conv,
"_structure",
"_unstructure",
)
assertconv.unstructure(Thing(1)) == {
"a" : "1",
}
deftag_attrs_hook_factory(cl):
base_hook=cattrs.gen.make_dict_unstructure_fn(cl, conv)
defhook(instance):
unstruct=base_hook(instance)
unstruct["_type"] =type(instance).__name__returnunstructreturnhooktagging_conv_a=cattrs.Converter()
tagging_conv_a.register_unstructure_hook_factory(attrs.has, tag_attrs_hook_factory)
use_class_methods(
tagging_conv_a,
"_structure",
"_unstructure",
)
# THIS IS WRONG. Does not have the tagasserttagging_conv_a.unstructure(Thing(1)) == {
"a" : "1",
}
tagging_conv_b=cattrs.Converter()
use_class_methods(
tagging_conv_b,
"_structure",
"_unstructure",
)
tagging_conv_b.register_unstructure_hook_factory(attrs.has, tag_attrs_hook_factory)
# THIS IS WRONG. Does not convert the sub value correctly via the metamethodasserttagging_conv_b.unstructure(Thing(1)) == {
"_type" : "Thing",
"a" : 1,
}
What I tried initially was to just inject the converter so it dispatches to the metamethods properly. But this causes infinite recursion, e.g.:
deftag_attrs_hook_factory(cl):
converter= ... # via closuredefhook(instance, converter):
unstruct=converter.unstructure(instance)
unstruct["_type"] =type(instance).__name__returnunstructreturnhook
I think that make_dict_unstructure_fn and friends should honor the metamethods for the passed in converter and break recursion. I'm not sure if this makes sense though... In any case this is a difficult case to handle generally.
The text was updated successfully, but these errors were encountered:
From comments in #558. Custom metamethods and
make_unstructure_dict_unstructure_fn
cannot be used together:What I tried initially was to just inject the converter so it dispatches to the metamethods properly. But this causes infinite recursion, e.g.:
I think that
make_dict_unstructure_fn
and friends should honor the metamethods for the passed in converter and break recursion. I'm not sure if this makes sense though... In any case this is a difficult case to handle generally.The text was updated successfully, but these errors were encountered: