简体   繁体   中英

What is the most Pythonic way to organise constants?

I use marshmallow and have a series of object serialization. Because of technical reasons, the names of the field and class can be the same.

For example,

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

class SampleField(Schema):
   # Some other fields

When I need to reference SampleField as a string in the code. I create constant and name it SAMPLE_FIELD = SampleField . Often I need to have the same constant in both places in the definition class and where it is used as a field.

How to organize it the way, it will not become messy?

The marshmallow field does not have to be named after the field name in serialiazed data.

Would this solve your problem?

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

class SampleFieldSchema(Schema):
   # Some other fields

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM