Skip to content

Hooking to determine type #140

@jpsnyder

Description

@jpsnyder
  • cattrs version: 1.4.0
  • Python version: 3.7.5
  • Operating System: Windows

Description

Is there a way to create a special hook that determines the class/type to use based on the results of a function. Similar to register_structure_hook_func(), but for the value?
This would help to support the common technique of including a _type in the dict to determine the correct class within a base class.

As well, it would allow one to modify the value before being structured.

class Element:
    """Some generic base class"""
    ...

    @classmethod
    def _get_class(cls, value: dict):
        try:
            class_name = value["_type"]
            del value["_type"]
        except KeyError:
            return cls
            
        for klass in Element.__subclasses__():
            if klass.__name__ == class_name:
                return klass
        return cls
   

cattr.register_structure_type_hook(Element._get_class, base=Element)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions