marshmallow-oneofschema icon indicating copy to clipboard operation
marshmallow-oneofschema copied to clipboard

Children schema doesn't get parent init values

Open jgourinda opened this issue 5 years ago • 1 comments

When using a parent schema the initialization value do get passed to the actual children schema. Use case: I want to be able to bypass the classic post_load make_object when I init a partial schema.

    @post_load
    def make_object(self, data: Dict) -> object:
        if self.__model__ is None or self.partial:
            return data
        return self.__model__(**data)

The problem is that if a use a parent OneOfSchema the final schema is instantiated withou any init parameters. See here and here in marshmallowoneofschema/marshmallow_oneofschema/one_of_schema.py

schema = type_schema if isinstance(type_schema, Schema) else type_schema()

jgourinda avatar Jun 10 '19 08:06 jgourinda

There is a pull request for that, but it is 1 year old and has conflicts : https://github.com/marshmallow-code/marshmallow-oneofschema/pull/15

Problem in this PR is that arguments cannot be passed to both the child class and parent class constructor. For instance parameter only would trigger an exception since the parent schema has no field.

One simple workaround is to wrap type_schema in a method that takes care of child schema initialization, in the parent constructor. Here is what I do:

from marshmallow_oneofschema import OneOfSchema

class ExtendedOneOfSchema(OneOfSchema):
    def __init__(self, *args, **kwargs):
        self._schema_args = args
        self._schema_kwargs = kwargs

        # Wrap schema initialization to add arguments
        self.type_schemas = {
            k: self.with_args(v) for k, v in self.type_schemas.items()
        }

        super(ExtendedOneOfSchema, self).__init__()

    def with_args(self, schema):
        def init_schema():
            return schema(*self._schema_args, **self._schema_kwargs)
        return init_schema

This works well for me, I'm not sure it generalizes well.

I'll be happy to create a PR for this if it is of any interest.

kevinadda avatar Jul 08 '19 09:07 kevinadda