0

我想使用从字典重新创建我的对象,cattr但看起来这不适用于设置为的嵌套字段None

这是一个解释问题的代码示例:

import attr 
import cattr

@attr.s(auto_attribs=True) 
class B(object):
    b :int = 0

@attr.s(auto_attribs=True) 
class A(object):
    a :int = 0
    b: B = None

x = A(1) 
x_dict  = attr.asdict(x) 

现在,如果 Iry 使用以下方法构造我的对象:

cattr.structure(x_dict,A)

我收到以下错误:

   if 'b' in o:
TypeError: argument of type 'NoneType' is not iterable

一种解决方法是在调用结构之前从字典中删除 None 字段:

del x_dict["b"]
cattr.structure(x_dict,A) 

我需要这样做吗?或者有更简单的解决方案

任何帮助深表感谢。

4

2 回答 2

1

下面是一个基于数据类的解决方案

from dataclasses import dataclass
from typing import List
from dacite import from_dict



@dataclass
class Dog:
    name:str
    age:int

@dataclass
class Person:
    name: str
    dogs: List[Dog] = None


data1 = [{'name':'jack','dogs':[{'name':'bark','age':12},{'name':'jumpy','age':3}]}]
persons1: List[Person] = [from_dict(Person,entry) for entry in data1]
print(persons1)

data2 = [{'name':'jack'}]
persons2: List[Person] = [from_dict(Person,entry) for entry in data2]
print(persons2)

输出

[Person(name='jack', dogs=[Dog(name='bark', age=12), Dog(name='jumpy', age=3)])]
[Person(name='jack', dogs=None)]
于 2021-09-15T08:09:54.480 回答
1

None不是有效的B. 您应该定义b为 type Optional[B]

from typing import Optional
import attr
import cattr


@attr.s(auto_attribs=True)
class B(object):
    b: int = 0


@attr.s(auto_attribs=True)
class A(object):
    a: int = 0
    b: Optional[B] = None


x = A(1)
x_dict = attr.asdict(x)
cattr.structure(x_dict, A)
于 2021-09-13T21:51:44.107 回答