从字典创建对象的简单库
dedict的Python项目详细描述
DEDICT
dedict是一个简单的无依赖关系库,允许您从字典创建数据对象。它目前在python 3.6和3.7上工作
为什么是Dedict?
已经有一些库允许您从json/字典创建对象,比如jsonpickle。但是,这些库通常依赖于存储在输入结构中的元数据来创建对象。这意味着序列化的对象中有噪音元数据,并且dictionary/json必须是与库一起生成的,才能转换回对象。
还有jsonstruct解决了元数据问题,但要求数据类为其参数定义“默认”值,以便它可以在运行时读取类型并了解如何创建对象。
dedict的目标是避免使用这些方法,并允许在不依赖输入数据中的元数据或数据类中的任意默认值的情况下创建对象。相反,dedict巧妙地利用了python 3.6中引入的type hints和variable annotations。
安装
pip install dedict
使用示例
classSomeDataClass(Dedictable):something:strwhatever:intsome_data_class=SomeDataClass.dedict({'something':'test','whatever':100})# output: SomeDataClass(something='test', whatever=100)
dedict也递归工作,这意味着您可以解析复杂的数据结构
classSomeChildClass(Dedictable):a:strb:strclassComplex(Dedictable):some_string:strchild:SomeChildClasscomplex=Complex.dedict({'some_string':'test','child':{'a':'hello','b':'world'}})
内置对象模型验证
dedict还通过检查数据结构中是否有不属于目标对象的字段,确保传递的数据实际上是您试图创建的对象的有效表示形式
classSample(Dedictable):something:strwhatever:strsample=Sample.dedict({'something':'else','whatever':'you want','hello':'world'})# raises: AttributeError('object Sample has no attribute named hello')
默认情况下,dedict不关心输入数据结构中缺少的属性,并将它们视为可选的。但是,您可以使用DedictableStrict
实现来强制执行完全验证。
classStrict(DedictableStrict):a:strb:strc:strs=Strict.dedict({'b':'hello','c':'world'})# raises: AttributeError('dictionary was missing mandatory attribute a to create an object of type Sample')
但是,如果您想要完全验证,但也需要将某些属性设置为可选,则dedict提供了一个新的类型注释,以便在使用严格实现时将属性标记为可选。
classStrict(DedictableStrict):a:OptionalAttr[str]b:strc:strs=Strict.dedict({'b':'hello','c':'world'})