Skip to content

Is there a way to add a "catch-all" fallback hook? #311

Closed
@yukw777

Description

@yukw777
  • cattrs version: 22.2.0
  • Python version: 3.9.12
  • Operating System: Ubuntu

Description

First of all, thanks for the awesome library!

My use-case is that I want to be able to serialize as much as I can by falling back to something like pickle for non-attrs classes. I understand that pickle can't serialize everything, but I'm just trying to cover as many classes as I can. Unstructuring is not a problem by using things like jsonpickle or the default option of orjson, but structuring is giving me a lot of problems. I've tried to use cattrs.register_structure_hook_func, but I haven't found a way to make it work. I guess one solution would be to find a way to check if a type is supported (either implicitly or explicitly) by the current converter or not, but I haven't found a good way to do so.

What I Did

# infinite recursion b/c of attrs class that have not been explicitly registered.
def fallback(d, t):
    if attrs.has(t):
        return cattrs.structure(d, t)
    return pickles.loads(d)
cattrs.register_structure_hook_func(lambda cls: True, lambda d, t: t.deserialize(d))
# fails on collections of attrs classes such as list[attrs]
def fallback(d, t):
    if attrs.has(t):
        return cattrs.structure_attrs_fromdict(d)
    return pickles.loads(d)
cattrs.register_structure_hook_func(lambda cls: True, lambda d, t: t.deserialize(d))

Any help would be greatly appreciated!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions