-
-
Notifications
You must be signed in to change notification settings - Fork 122
Closed
Description
- 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
Labels
No labels