python - 使用 cattr/attr 从 dict 构造一个对象,默认设置为 None
问题描述
我想使用从字典重新创建我的对象,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)
我需要这样做吗?或者有更简单的解决方案
任何帮助深表感谢。
解决方案
下面是一个基于数据类的解决方案
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)]
推荐阅读
- vim - 如何将连续命令映射到键
- sqlite - Sqlite3 不会删除数据,即使它说已删除
- flutter - 如何使用firebase和flutter为食谱应用程序添加最喜欢的功能?
- javascript - 移除带有额外参数的事件监听器
- javascript - 基于滚动跟踪div内的像素位置
- python - makemigration 后只出现 2 列
- amazon - 如何使用 Amazon Selling Partner Api 更改我的产品图片?
- woocommerce - 如果通过自定义脚本下订单,则无法完成 Woocommerce 付款
- spring-boot - Resilience4J Kotlin 协程定义回退方法
- javascript - 在JS中使用箭头函数之外的变量