如何解决这个特定的 python 循环导入?

How can I solve this specific python circular import?

有人可以帮我解决这个 python 循环导入吗?

文件 measurement_schema.py 导入 elementary_process_schema。文件 elementary_process_schema.py 导入 measurement_schema.

我需要在每个声明的 class 的最后一行使用引用的 class。例如:measurement_schema.py的最后一行:elementary_processes = fields.Nested(ElementaryProcessSchema, many=True)

完整代码:

measurement_schema.py

from marshmallow import fields

from api import ma
from api.model.schema.elementary_process_schema import ElementaryProcessSchema


class MeasurementSchema(ma.Schema):


    id = fields.Int(dump_only=True)
    name = fields.Str()
    description = fields.Str()
    created_on = fields.Str()

    elementary_processes = fields.Nested(ElementaryProcessSchema, many=True)

elementary_process_schema.py

from marshmallow import fields

from api import ma
from api.model.schema.ar_rl_schema import ARRLSchema
from api.model.schema.data_item_schema import DataItemSchema
from api.model.schema.elementary_process_type_schema import ElementaryProcessTypeSchema
from api.model.schema.measurement_schema import MeasurementSchema


class ElementaryProcessSchema(ma.Schema):
    id = fields.Int(dump_only=True)
    name = fields.Str()
    operation = fields.Str()
    reference = fields.Str()
    created_on = fields.Str()

    elementary_process_type = fields.Nested(ElementaryProcessTypeSchema)
    data_itens = fields.Nested(DataItemSchema, many=True)
    AR_RLs = fields.Nested(ARRLSchema, many=True)

    measurement = fields.Nested(MeasurementSchema)

我知道有很多关于这个问题的话题。但是,我无法解决我的特定循环引用问题。

这是 ORM 和 python 的常见问题,通常以相同的方式解决:您通过名称(字符串)而不是引用(class/instance)来识别关系。它在棉花糖文档中有详细记录:

https://marshmallow.readthedocs.io/en/stable/nesting.html#two-way-nesting

简而言之,尝试这样的事情(我对棉花糖的经验为 0,所以这绝不是经过测试的):

elementary_processes = fields.Nested(ElementaryProcessSchema, many=True)
# would become:
elementary_processes = fields.Nested("ElementaryProcessSchema", many=True)

measurement = fields.Nested(MeasurementSchema)
# becomes:
measurement = fields.Nested("MeasurementSchema")