Creating nested dataclass objects in Python

后端 未结 6 1672
礼貌的吻别
礼貌的吻别 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:41

    Very important question is not nesting, but value validation / casting. Do you need validation of values?

    If value validation is needed, stay with well-tested deserialization libs like:

    • pydantic (faster but messy reserved attributes like schema interfere with attribute names coming from data. Have to rename and alias class properties enough to make it annoying)
    • schematics (slower than pydantic, but much more mature typecasting stack)

    They have amazing validation and re-casting support and are used very widely (meaning, should generally work well and not mess up your data). However, they are not dataclass based, though Pydantic wraps dataclass functionality and allows you to switch from pure dataclasses to Pydantic-supported dataclasses with change of import statement.

    These libs (mentioned in this thread) work with dataclasses natively, but validation / typecasting is not hardened yet.

    • dacite
    • validated_dc

    If validation is not super important, and just recursive nesting is needed, simple hand-rolled code like https://gist.github.com/dvdotsenko/07deeafb27847851631bfe4b4ffffd9059 is enough to deal with Optional and List[ Dict[ nested models.

提交回复
热议问题