0

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?

user783836
  • 3,099
  • 2
  • 29
  • 34
  • `MethodSchema` doesn't exist until you've finished defining it, but the inner `MethodParamsSchema` is already complete; did using `fields.Nested(MethodParamsSchema)` in your second stricture not work? – jonrsharpe Feb 20 '18 at 08:10
  • doh! That works! I had tried that with the field declarations above the inner class, which failed as the inner class hadn't been declared by the time the fields were parsed and then didn't try it again when I switched the field and inner class declaration order. @jonrsharpe if you make your comment an answer I'll accept it. – user783836 Feb 20 '18 at 08:41

1 Answers1

0

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

params = fields.Nested('MethodParamsSchema')
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Szabolcs
  • 3,990
  • 18
  • 38
  • 1
    ta. Looks like I can also just use the class name as long as I declare the inner class before the field: `params = fields.Nested(MethodParamsSchema)` – user783836 Feb 20 '18 at 12:55