python - 组织常量的最 Pythonic 方式是什么?
问题描述
我使用marshmallow
并拥有一系列对象序列化。由于技术原因,字段和类的名称可以相同。
例如,
class Sample(Schema):
SampleField = fields.Nested(SampleField)
class SampleField(Schema):
# Some other fields
当我需要SampleField
在代码中引用为字符串时。我创建常量并命名它SAMPLE_FIELD = SampleField
。通常我需要在定义类的两个地方以及它用作字段的地方都有相同的常量。
怎样整理它的方式,才不会变得乱七八糟?
解决方案
棉花糖字段不必以序列化数据中的字段名称命名。
这会解决你的问题吗?
class SampleSchema(Schema):
sample_field = fields.Nested(SampleFieldSchema, data_key='SampleField')
class SampleFieldSchema(Schema):
# Some other fields
推荐阅读
- reactive-programming - BlockHound 将 WebClient 的 ExchangeFunction 的 .next() 方法检测为阻塞
- javascript - 为什么
显示溢出子元素? - sql - 如何在 HANA DB 的 IN 运算符中使用变量?
- reactjs - 如何在滚动时使用 react-spring 从左到右正确移动 React 组件?
- google-sites - 将 atari-embeds.googleusercontent.com 附加到我的 API 调用的 Google 协作平台 - 如何仅使用我的域进行调用?
- typescript - 在 Nest JS 中发出 http 请求时出现 httpService 未定义错误
- android - 如果在android中将其重命名为不同的文件扩展名,如何获取实际文件类型?
- android - `DataBindingUtil` 中的 `bind`、`inflate` 和 `setContentView` 有什么区别
- java - Struts Action 类中的不可序列化属性
- ubuntu - 如何将 Windows 10 WSL 2 Linux 发行版移动到另一个位置