Search code examples
pythonmarshmallow

Inner class as nested schema in Marshmallow?


Is it possible to use an inner class as a nested schema in Marshmallow (https://marshmallow.readthedocs.io/en/latest/)?

I am trying to represent a hierarchical schema in Marshmallow which appears to be done through nested schemas. For example, I have a Method object, which has a Params attribute, which itself is an object. I could represent it as:

class MethodParamsSchema(Schema):
    a = fields.String()
    b = fields.Int()

class MethodSchema(Schema):
    name = fields.String()
    params = fields.Nested(MethodParamsSchema)

What I would like to do is:

class MethodSchema(Schema):

   class MethodParamsSchema(Schema):
        a = fields.String()
        b = fields.Int()

    name = fields.String()
    params = fields.Nested('MethodSchema.MethodParamsSchema')

but this fails with the error:

Class with name 'MethodSchema.MethodParamsSchema' was not found. You may need to import the class.

The reason I would like to do this is because my schemas are fairly hierarchical and I'd like to group related items together. Is there a way to achieve this?


Solution

  • Changing 'MethodSchema.MethodParamsSchema' to 'MethodParamsSchema' when defining the nested field resolves the problem for me:

    params = fields.Nested('MethodParamsSchema')