首页 > 解决方案 > 组织常量的最 Pythonic 方式是什么?

问题描述

我使用marshmallow并拥有一系列对象序列化。由于技术原因,字段和类的名称可以相同。

例如,

class Sample(Schema):
    SampleField = fields.Nested(SampleField)

class SampleField(Schema):
   # Some other fields

当我需要SampleField在代码中引用为字符串时。我创建常量并命名它SAMPLE_FIELD = SampleField。通常我需要在定义类的两个地方以及它用作字段的地方都有相同的常量。

怎样整理它的方式,才不会变得乱七八糟?

标签: pythonconstantspackagingmarshmallowcode-structure

解决方案


棉花糖字段不必以序列化数据中的字段名称命名。

这会解决你的问题吗?

class SampleSchema(Schema):
    sample_field = fields.Nested(SampleFieldSchema, data_key='SampleField')

class SampleFieldSchema(Schema):
   # Some other fields


推荐阅读