Search code examples
pythonmarshmallow

How can I solve this specific python circular import?


Can someone help me with this python circular import?

The file measurement_schema.py imports elementary_process_schema. And the file elementary_process_schema.py imports measurement_schema.

I need to use the referenced class in the last line of each declared class. e.g.: The last line of measurement_schema.py: elementary_processes = fields.Nested(ElementaryProcessSchema, many=True)

Full code:

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)

I know there are many topics about that issue. However, I cannot solve my specific circular reference issue.


Solution

  • This is a common problem with ORMs and with python it's often solved the same way: you identify the relationship by name (string) instead of reference (class/instance). It's well documented in marshmallows doc here:

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

    in short, try something like this (I have 0 experience with marshmallow, so this is in no way tested):

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

    and

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