Creating nested dataclass objects in Python

后端 未结 6 1793
礼貌的吻别
礼貌的吻别 2020-12-09 10:10

I have a dataclass object that has nested dataclass objects in it. However, when I create the main object, the nested objects turn into a dictionary:

@datacl         


        
6条回答
  •  悲&欢浪女
    2020-12-09 10:49

    I have created an augmentation of the solution by @jsbueno that also accepts typing in the form List[].

    def nested_dataclass(*args, **kwargs):
        def wrapper(cls):
            cls = dataclass(cls, **kwargs)
            original_init = cls.__init__
    
            def __init__(self, *args, **kwargs):
                for name, value in kwargs.items():
                    field_type = cls.__annotations__.get(name, None)
                    if isinstance(value, list):
                        if field_type.__origin__ == list or field_type.__origin__ == List:
                            sub_type = field_type.__args__[0]
                            if is_dataclass(sub_type):
                                items = []
                                for child in value:
                                    if isinstance(child, dict):
                                        items.append(sub_type(**child))
                                kwargs[name] = items
                    if is_dataclass(field_type) and isinstance(value, dict):
                        new_obj = field_type(**value)
                        kwargs[name] = new_obj
                original_init(self, *args, **kwargs)
    
            cls.__init__ = __init__
            return cls
    
        return wrapper(args[0]) if args else wrapper
    

提交回复
热议问题